mohas
mohas

Reputation: 1931

JS variable hoisting inside closure

JS hoists all variables within scope so why does this code throw an exception:

(function() {

  function i() {
      console.log(a.a);
  }
  i();
  var a = { a:1 };
})()

While this one works:

(function() {
  var a = { a:1 };
  function i() {
      console.log(a.a);
  }
  i();

})()

What behavior of interpreter causes this?

Upvotes: 1

Views: 45

Answers (1)

6502
6502

Reputation: 114481

The variable a is already visible, but its value {a:1} is not assigned until the var is reached by the execution. Things are somewhat different for local functions declared with function foo(){...} because the names are bound to the respective functions/closures before the execution starts.

If you call the closure i before assigning a a value you get the problem, however with

(function(){
     function i(){
         console.log(foo());
     }
     i();
     function foo() { return 42; }
})();

the output is 42 and there's no error.

Note that this is true because the function statement is used... changing the code to

(function(){
     function i(){
         console.log(foo());
     }
     i();
     var foo = function(){ return 42; }
})();

gives an error because in this case when i() is executed foo is not yet bound to the function (like in your case).

Upvotes: 4

Related Questions