I am developing with JavaScript for a while and I am used to a lot of it quirks. But even after years of using this language you still find new curiosities. Today a struggled a while with this one.
Considering this piece of JavaScript code:
-
var i = 10;
-
function foo() {
-
i++; // i is now 11
-
console.log("foo1: "+i);
-
i = 0; // i is now 0
-
console.log("foo2: "+i);
-
};
-
console.log("global1: "+i); // should be 10
-
foo();
-
console.log("global2: "+i); // and now 0
Ok. That’s fine. Now we change the code a little bit to this one:
-
var i = 10;
-
function foo() {
-
i++; // is now 11
-
console.log("foo1: "+i);
-
var i = 0; //create a new variable with value 0
-
console.log("foo2: "+i);
-
};
-
console.log("global1: "+i); // expect: 10
-
foo();
-
console.log("global2: "+i); // expect: 11
What do you expect? I was quite surprised: continue reading…