Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local Javascript scoping issue

If I do this:

var a = 0;

(function () {
    var a = a; //want to make local a = global a
    ++a;
    console.log("fn",a);
})();

console.log(a);​

The output is:

fn NaN
0

Why does a inside of the self executing function become NaN?

I know it works fine if I do:

(function () {
    var b = a;
    ++b;
    console.log("fn",b); // fn 1
})();

But if I go the way of the first version, it has the NaN issue.

Why is this happening?

like image 732
Naftali Avatar asked Jul 12 '12 17:07

Naftali


2 Answers

var a = a; is actually var a; a = a; due to variable hoisting. This means at the time of the assignment the old a is already shadowed by the new one (which is undefined).

The easiest way to avoid issues like that is passing the value as a parameter:

(function (a) {
    ++a;
    console.log("fn",a);
})(a);

In case a is a global variable you could also use var a = window.a; like woz suggested - but since having global variables is usually a bad idea better stay with the parameters.

like image 152
ThiefMaster Avatar answered Sep 28 '22 08:09

ThiefMaster


The a variable inside your function expression shadows the a variable declared on the outer scope.

It becomes NaN, since in the assignment:

var a = a;

The right-side a it's actually referring to the a in the local scope.

Variable declarations are done before the function actually starts to be executed, this is commonly known as 'hoisting'.

Since it's the same variable, it holds the undefined value, and when you try to add any number to this value, it becomes NaN:

console.log(undefined + 0);
like image 29
Christian C. Salvadó Avatar answered Sep 28 '22 09:09

Christian C. Salvadó