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?
var a = a;is actuallyvar a; a = a;due to variable hoisting. This means at the time of the assignment the oldais already shadowed by the new one (which isundefined).The easiest way to avoid issues like that is passing the value as a parameter:
In case
ais a global variable you could also usevar a = window.a;like woz suggested – but since having global variables is usually a bad idea better stay with the parameters.