0
votes

I am having trouble understanding why the following code prints 1 and not 10. I thought that console.log would print 10 because if a variable is not declared within a function it is part of the global scope.

If I remove the line, function a(){}, the console.log statement prints 10. Can someone please explain why the presence of this line affects the value of a.

Additionally, if this question can be refined I would appreciate any suggestions

function b() { 
    a = 10; 
    return;
    function a(){}
} 
var a = 1; 
b(); 

console.log(a);
3

3 Answers

0
votes

Just add console.log(a); to your function and you will realize that 'a' is a function that has local scope, which means, it inside function b() and can't really be called from outside. Hence, the value of a remains as 1, as nothing really affects it.

function b() { 
    console.log(a);
    a = 10; 
    return;
    function a(){}
} 
var a = 1; 
b(); 

console.log(a);
0
votes

Function declarations create local variables, and all declared variables are hoisted to the top of their containing function scope. Thus, you have something equivalent to:

function b() { 
    function a(){}
    a = 10; 
    return;
} 

which is in turn roughly equivalent to

function b() { 
    var a = function(){}
    a = 10; 
    return;
} 

As you can see in this form, it's clear that a is a local variable, so a = 10 assigns a value to the local a, not the global a.

0
votes

Because both function declarations and variables are treated similarly under the hood.

When a function is called, its contents are first parsed to configure the stack frame ready for its execution.

As part of this process, function declarations and variables are inserted as identifier/value pairs into the same data structure (Environment Record inside the Lexical Environment) inside the stack frame (Execution Context) created when a function is called.

So by declaring a function a inside b, you create an identifier named "a" in the Environment Record created for the call to b, shadowing a in the outer context.

So a in the outer context remains 1.