Vikram Bhaskaran
Vikram Bhaskaran

Reputation: 417

Function Scopes Understanding Unclear

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?

Upvotes: 5

Views: 67

Answers (2)

King Friday
King Friday

Reputation: 26076

You code is misleading and in a style that makes people think execution order matters. The standard JavaScript engine these days will take that and reformat prior to running it to:

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

Now you can understand what is actually happening. "a" is declared again inside the function "b" so there is actually two "a" variables now. One is "window.a" and the other one is "b var a" but NOT "b.a" because its not accessible outside of the closure or function.

In other words, you get what you code for.

Please make your code readable and don't confuse the point.

Upvotes: 4

Pointy
Pointy

Reputation: 413712

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.

Upvotes: 6

Related Questions