JavaScript multiple assignment
In JavaScript, you can assign multiple variables in the same line of code:
// prettier-ignore
var a = 1, b = 2;
console.log(a, b); // 1 2
And you can also assign several variables together:
// prettier-ignore
function f() {
var a = b = 2;
}
f();
console.log(a); // ReferenceError: a is not defined
console.log(b); // 2
What just happened? Assignment is right associative (pairs from right to left), so you can think of the previous code as being the same as:
// prettier-ignore
function f() {
var a = (window.b = 2);
// same as var a = b = 2;
}
f();
console.log(a); // ReferenceError: a is not defined
console.log(b); // 2
The right most pair is like an assignment when you forget to put the var keyword.
You can also think about var a = (b = 3)
as:
b = 3;
var a = b;
Avoid creating global variables (window.a is a global variable). If you create global variables, you can create bugs when you use the same variable name.
Questions
What's the output?
function f() {
var a = (b = 5);
}
f();
console.log(b === 5);
What's the output?
function f() {
var a = (b = 5);
}
f();
console.log(a);
What's the output?
function f() {
var a = 2, b = 5
}
f()
console.log(typeof b === 'undefined')
What's the console output?
function f() {
//prettier-ignore
var a1 = a2 = 1
}
f();
console.log(window.a1, window.a2);
What's the console output?
function f() {
//prettier-ignore
var a1 = 1, a2 = 1
}
f();
console.log(window.a1, window.a2);