Volume Variables (Ascent) in Javascript

One of my friends was taking an online quiz, and he asked me this question, which I could not answer.

var global = false; function test() { global = true; return false; function global() {} } console.log(global); // says false (As expected) test(); console.log(global); // says false (Unexpected: should be true) 

Assuming functions rise above with var variables, try this.

 var foo = 1; function bar() { return foo; foo = 10; function foo() {} var foo = 11; } bar(); console.log(foo); //says 1 (But should be 11) Why 1 this time ?? 

Here is the JSBin Demo and JSBIN Demo2 to play with.

PS: If we remove function global() {} from test() , then it works fine. Can someone help me understand why this is happening?

+7
javascript scope global-variables
source share
2 answers

var statements and declarations of declarations of functions "rise" to the beginning of their encompassing field.
Therefore, function global(){} in your function creates the local name global .

The global assignment within your functions is associated with this local name. Here you can β€œrewrite” it with a lift to understand how the compiler sees it:

 function test() { var global = function() {}; // hoisted; 'global' now local global = true; return false; } 
+8
source share

I will answer the second part of your question,

Assuming functions go up along with var variables

 bar(); console.log(foo); //says 1 (But should be 11) Why 1 this time ?? 

Instead, you should try console.log(bar()); console.log(foo); console.log(bar()); console.log(foo); . However, what makes the upgrade for your function is:

 function bar() { var foo; function foo() {} return foo; foo = 10; foo = 11; } 

So, you should expect a function to return, since your variable assignments are after the return . Both var and the function declaration make foo local variable, so global foo = 1 never changes.

+2
source share

All Articles