When learning JavaScript I encountered a problem about hoisting that is if you run the code below, what you will get?
f1();
console.log(b);
console.log(a);
function f1() {
var a = b = 1;
console.log(a);
console.log(b);
}
The answer is you get three 1 ,and an error which makes sense due to hoisting.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
Based on the result, I can infer that var a = b = 1; is equals to var a = 1; b = 1;
My problem is Why?
I tried to google it but it seems there is no explanation about the order that var and ‘=’ are executed. I would appreciate it that you would show me how the var a = b = 1; is executed step by step.
>Solution :
Because assignment is an expression which evaluates to the assigned value. So this operation:
b = 1
not only assigns the value of 1 to b but also the entire expression evaluates to the value of 1. Since it’s an expression which evaluates to a value, it can be used in place any time a value is needed.
This needs a value:
var a = (something)
So you can use any expression, for example:
var a = (b = 1)
And the parentheses are unnecessary since the assignment to a won’t occur until the expression is evaluated and a value produced:
var a = b = 1
What wouldn’t work is to both declare and assign as an expression. For example:
var a = (var b = 1)
Because the declaration is not an expression, it’s a statement. Statements can be thought of as "a line of code" and can’t be dropped in-place in the middle of other code.
You can test this in your browser’s debugging tools by entering code directly onto the console. If you do this:
var a = 1
The console will print undefined, because the statement produced no value (even though it did assign a value to a). If you do this:
b = 1
The console will print 1 because the expression produced a value (as well as assigned a value to b).
Regarding the rest of the code being tested in the question, the key difference between a and b is that a is declared and thus has a specific scope, whereas b is not declared and thus defaults to a property on the window object which is accessible anywhere.