(function foo() { var a=b=c=1 }())
When I try to log a will return a not defined err, however, when I try to log b or c will return the value 1. It's wicked.
b and c are added into the window object and get their values as 1. But a is declared via var. This means that a is visible only in the function context and not outside from it.
Your code is equivalent
(function foo() {
c = 1;
b = c;
var a = b;
}())
however, when I try to log b or c will return the value 1.
Because you didn't localized the scope (inside the function) of b and c by using var or let or const.
Without var, let or const, these variable will take the scope in which this function is defined.
If the outer scope (not outermost) also doesn't localize those variables, then parent scope is checked again till the outermost scope (window). And the variable gets added to outermost scope if no local scope is defined for them. for example
function a() {
(function foo() {
var a = b = c = 1;
}());
console.log(b, c); //print 1,1
}
a();
console.log(b, c); //print 1,1
However, if these variables are defined in outer scope, then they don't get added to the outermost (window) scope. For example, following will throw an error.
function a() {
var b,c;
(function foo() {
var a = b = c = 1;
}());
a();
console.log(b, c);
}
console.log(b, c);
var is only for a since you are using an assignment expression. You meant var a = 1, b = 1?If you have lots of constructs where you want to initialise to some constants and you can use ES6 features the following is a nice way to do it.
//store function in your lib
function* initVar(value) {
while (true) yield value;
}
//using function
let
[a,b,c] = initVar(0),
[d,e,f] = initVar("xyz"); //not just limited to numbers.
console.log(a,b,c,d,e,f);
(function foo() { "use strict"; var a=b=c=1 }())