Question

Hey all I'm trying to understand JavaScript closures and have a quick question on this piece of code,

var a = 5;

function woot() {
  console.log('a == 5 woot: ' + (a == 5).toString());

  var a = 6;

  function test() {
    console.log('a == 6 test: ' + (a == 6).toString());
  }

  test();
}

console.log('a == 5 outside: ' + (a == 5).toString());

woot();

console.log('a == 5 end: ' + (a == 5).toString());

Output:

a == 5 outside: true
a == 5 woot: false
a == 6 test: true
a == 5 end: true

I was expecting the all the outputs to be true but a is undefined in the first line of woot(). Why is this?

Était-ce utile?

La solution

When you declare a variable anywhere inside the function, the variable will become local to that function, as all the variable declarations are moved to the top of the function.

In your case,

  console.log('a == 5 woot: ' + (a == 5).toString());

  var a = 6;

Before you assign 6 to a, a will be undefined, but the scope will be local.

You might want to read about variable hoisting example in the MDN docs.

And as per the same MDN var doc,

The scope of a variable declared with var is the enclosing function

Autres conseils

var statements are hoisted.

Even though it appears below the console.log statement, var a = 6; creates a local variable in the scope of the function before the console.log statement runs.

(It doesn't assign the value to it until that line is reached though).

What is hoisted?

Whenever you declare a variable in javascript, javascript engine first initializes variables and then processes next methods..hence even if you declare variable at the end, javascript engine will process it first.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top