1

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?

4 Answers4

2

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.

Mitya
  • 32,084
  • 8
  • 49
  • 92
2

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.

Patrick Hollweck
  • 3,639
  • 2
  • 19
  • 27
1

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.

-1

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

matek997
  • 311
  • 1
  • 11