Javascript: the Scope Pitfall II

Hello, and welcome to the second part of “Javascript: The Scope Pitfall”. Let’s get started, shall we?

What does the following code print?

var n = 0;
function add() {
    var m = n + 1;
    print(m);
}
add();

That was easy, right? The answer, of course is 1, because 0 + 1 == 1. Alright, a slight variation on the same example:

var n = 0;
function add2() {
    var n = n + 1;
    print(n);
}
add2();

What does this print? If your answer is NaN (not a number), you can stop reading. If you think the answer is 1 (as I did), read on. What is happening here? In my previous post I explained that Javascript lifts variable declarations to the top of the function. So, this code is equivalent to:

var n = 0;
function add2() {
    var n;
    n = n + 1;
    print(n);
}
add2();

It also turns out that when a previously undeclared variable (in this scope) is declared it is initialized to undefined. So we get:

var n = 0;
function add2() {
    var n = undefined;
    n = n + 1;
    print(n);
}
add2();

Any calculation involving undefined will return NaN, so naturally it will indeed print NaN. You can rewrite the code a little bit to make it print 1 again:

var n = 0;
var oldN = n;
function add3() {
    var n = oldN + 1;
    print(n);
}
add3();

It took me a while to figure this one out, though, when I ran into it. Just thought I would share.