how come the output of this IIFE is 5?
(function() {
var a = b = 5;
})();
console.log(b);
I tried console.log(a) but it gives a reference error as expected how come 'b' is alive in global scope?
how come the output of this IIFE is 5?
(function() {
var a = b = 5;
})();
console.log(b);
I tried console.log(a) but it gives a reference error as expected how come 'b' is alive in global scope?
This is happening simply because you're declaring b
as a global variable, not a local one.
(function() {
var a = b = 5;
})();
It may look like it's being defined locally because of var
, but that applies to a
only.
Interesting question. Though it is not related to IIFE's or hoisting at all. Notice how "a" is not defined!
Your code sample
function test() {
var a = b = 5;
}
is semantically equivalent to this:
function test() {
var a = 5;
// this is essentially the same as `window.b = a`
b = a;
}
since you did not declare "a" (aka var a;
) it ends up in the global scope.
In strict mode this would not work.
That's because of "leaking", which means to unintentionally make locally declared variables available to the global scope. More informations about can be found here. Let's split your code:
var a = b = 5;
This means: a
takes the value of b
, which is 5. The variable b
is implicitly declared and initialised in this case (with b = 5
), and since you're not specifying its block scope (that's because var
is referring to a
, not b
) it's bounded to the global scope.
that`s behavior is related to scope in non "strict mode",
when function is trying to execute, it find a function scope variable called a, and you don`t have access to it from outer scope and it will facing and error.
for the b variable it couldn't find declaration and go one level up and asked global scope about variable b and scope manager can`t find any var b, it will create it right away in global scope for you, result is you can log it in global scope, this thing calls (dynamic variable).
From documentation.
The scope of a variable declared with var is its current execution context and closures thereof, which is either the enclosing function and functions declared within it