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:

  1. var i = 10;
  2. function foo() {
  3.         i++; // i is now 11
  4.         console.log("foo1: "+i);
  5.         i = 0; // i is now 0
  6.         console.log("foo2: "+i);
  7. };
  8. console.log("global1: "+i); // should be 10
  9. foo();
  10. console.log("global2: "+i); // and now 0

Ok. That’s fine. Now we change the code a little bit to this one:

  1. var i = 10;
  2. function foo() {
  3.         i++; // is now 11
  4.         console.log("foo1: "+i);
  5.         var i = 0; //create a new variable with value 0
  6.         console.log("foo2: "+i);
  7. };
  8. console.log("global1: "+i); // expect: 10
  9. foo();
  10. console.log("global2: "+i); // expect: 11

What do you expect? I was quite surprised: continue reading…