# Javascript: the Scope Pitfall II

By **Zef Hemel**

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.