Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Scopes Understanding Unclear

Tags:

javascript

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

How is the output of 1 displayed for a? What does the

return;
function a() {}

within the function body perform?

like image 957
Vikram Bhaskaran Avatar asked Dec 16 '11 22:12

Vikram Bhaskaran


1 Answers

You declare a symbol "a" in the function with its last line. That's the "a" affected by the assignment statement.

Function declaration statements are hoisted up to the top of the function and are interpreted first. Thus, the assignment statement effectively happens after you've declared a function (local to the "b" function) named "a". The assignment, therefore affects that symbol, not the global "a".

Remember that variables aren't typed, so the fact that you've bound a name to a function doesn't prevent it from being assigned a numeric value later.

like image 99
Pointy Avatar answered Sep 28 '22 15:09

Pointy