How does variable assignment work in JavaScript?
In the first example, you are setting a property of an existing object. In the second example, you are assigning a brand new object.
a = b = {};
a
and b
are now pointers to the same object. So when you do:
a.foo = 'bar';
It sets b.foo
as well since a
and b
point to the same object.
However!
If you do this instead:
a = 'bar';
you are saying that a
points to a different object now. This has no effect on what a
pointed to before.
In JavaScript, assigning a variable and assigning a property are 2 different operations. It's best to think of variables as pointers to objects, and when you assign directly to a variable, you are not modifying any objects, merely repointing your variable to a different object.
But assigning a property, like a.foo
, will modify the object that a
points to. This, of course, also modifies all other references that point to this object simply because they all point to the same object.
Javascript, what happens when we assign value to read-only data property such as string length?
The assignment operator always returns the right-hand value. Hence, passing the expression inside the console.log function returns the right-hand value, in your case 3.
Assigning any value to the length property of a string has no effect.
let myString = "Hello,World!";
myString.length = 4;
console.log(myString);
// expected output: "Hello,World!"
console.log(myString.length);
// expected output: 12
JavaScript: Order in which variable assignment takes place
With var
things are a little different, because of hoisting.
Hoisting works with variables too, so you can use a variable in code before it is declared and/or initialized.
However JavaScript only hoists declarations, not initializations! This means that initialization doesn't happen until the associated line of code is executed, even if the variable was originally initialized then declared, or declared and initialized in the same line.
Example:
'option strict';
function myFunction() {
console.log(foo);
// => undefined
var sentence = 'my,array,of,strings';
var foo = sentence.split(',');
console.log(foo);
// => ['my', 'array', 'of', 'strings']
}
myFunction();
JavaScript OR (||) variable assignment explanation
See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.
Why is this method of variable assignment causing issues?
The difference is that with the second one, you're trying to assign to a properties
variable that you haven't declared. The var
only applies to prop
, not properties
because properties
is on the right-hand side of the =
after prop
, so it's part of the initializer for prop
. Here's how it's grouped:
var prop = (properties = this.properties);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^−−−− initializer for `prop`
In loose mode, that means you're falling prey to what I call The Horror of Implicit Globals — it creates a global called properties
. In strict mode, assigning to an undeclared identifier is the error it always should have been. (All new code should be written using strict mode.)
You can declare multiple variables with var
, etc., but you can't assign to them all using the same value source (without repeating it).
You could do:
var prop, properties;
prop = properties = this.properties;
if you liked. Or alternatively:
var prop = this.properties, properties = prop;
That works because the initializers in a var
(or let
or const
) with multiple declarations are executed in source code order, left-to-right, so prop = this.properties
happens before properties = prop
does.
Side note: var
shouldn't be used in new code, use let
or const
. (If you have to support obsolete JavaScript engines, you can transpile modern code to ES5.)
JavaScript variable assignment with OR vs if check
IMHO the use of the OR ||
for the purposes of assignment is perfectly valid and is good practice. We certainly use it in our projects and I've seen it used in lots of 3rd party projects that we use.
The thing you need to be aware of is how certain JavaScript objects can be coerced to be other values. So for example, if you're ORing values such as ""
, false
or 0
then they are treated as false... this means that when you have the following:
function f(o) {
var x = o || -1;
return x;
}
Calling:
f(0)
...will return -1... but calling
f(1)
Will return 1 ... even though in both cases you passed a number - because 0 is treated as false -1 is assigned to x.
...that said, as long as you're aware of how the OR operator will treat the operands that you use with it - then it is good JavaScript practice to use it.
Reading in a file, how does variable assignment and scope work?
if you look in the code from that page. The csv file contains salesperson
and sales
.
1 - You are correct in saying that the files is read in and the contents are assigned to data
2 - Kind of. You should look up what forEach
does and its format. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
But yes d
in this case is the reference to each datum in your data. Given the csv, each datum has a sales
property and a salesperson
property.
How can you then reference "d" outside of the foreach loop? Isn't it local to the loop? what variable type is "d.sales", some kind of reference to object d? And finally, where the heck did "d.salesperson" get created?
d
is just a reference. You can name it anything you want. Its just a reference to each of the datum within the data. They are not the same d
, though they reference the same datum.
data.forEach(function(value, index, array){});
The forEach
function is a loop that has access to the following items within the data its looping over, value
- which is each datum within the array, index
which is the index of that value, and array
which is the array itself. The d
in your case is the name given to the value
part of the function.
When d3 reads in the file it creates an array of objects each with properties based on the headers in the csv file. in this case its like this:
[{
"salesperson": "Bob",
"sales": 33
}, {
...
}]
You should really do some basic javascript before trying to pull apart a d3 graph. Also if youre not trying to do a graph and only trying to read a csv file, d3 is overkill.
Javascript: || operator for variable assignment
- Yes. If
x
has a truthy value, it will be assigned back to itself. If it doesn't, the default'some value'
will be assigned to it. - There may be a tiny performance benefit in example 2, but example 1 is the standard idiom. Consistency with other programmers is useful because they'll understand your code more easily. Unless you're doing lots of default value initialization in a large loop, the performance gain should be negligible.
Related Topics
Convert String in Dot Notation to Get the Object Reference
Setting Query String Using Fetch Get Request
Referencing "This" Inside Setinterval/Settimeout Within Object Prototype Methods
Converting .Net Datetime to JSON
How to Compare Two Time Strings in the Format Hh:Mm:Ss
How to Process Each Letter of Text Using JavaScript
How to Add a Tooltip to an Svg Graphic
Is JavaScript an Untyped Language
What's the Recommended Way to Extend Angularjs Controllers
Regular Expression for Password Validation
How to Limit Google Autocomplete Results to City and Country Only
How to Destructure Object Properties with Key Names That Are Invalid Variable Names
Is There a Built-In Way to Loop Through the Properties of an Object