5

1st test:

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

2nd test:

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

In the first test, a is equal to 1, although I set it to 10 in the method. In the second test, I set it to 10 and it is set to 10 when I output it.. How does this work?

1

4 Answers 4

3

The function declaration function a() {} declares a variable name a in the local scope of your b function (and assigns it the function). When you are assigning to a, you will assign to that local variable not the global one.

With hoisting applied, your code is equivalent to

var b = function b() {
    var a = function a() {};
    a = 10;
    return;
}
var a = 1;
b();
alert(a);    // 1, obvious now
Sign up to request clarification or add additional context in comments.

Comments

2

Because the hoisting creates a local variable a that masks the global one before you try to assign a value to it.

1 Comment

I see. Quite tricky. Thank you for your quick reply.
0

In your first test, you create a function which is stored in the local variable a:

function b() {
    a = 10;
    return;
    function a() {} // can be called using a() inside this function
}

So you could call this function using a() inside your function b(). Try:

function b() { 
    a(); // alerts "hi"
    a = 10;
    return;
    function a() { alert("hi"); }
}

Now, you store in the local variable a the number 10 instead of the function. The global variable remains unchanged, therefore your outer alert still shows 1.

Comments

0

The first example is interpreted (by JavaScript) as:

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

In JavaScript, all local variables (in this case the local variable a that will hold the function) are declared at the top of the function.

The local variable a gets set to 10 rather than the global. It then ceases to exists after return.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.