created by Brian LeRoux & Andrew Lunny. sparodically uncurated by David Trejo.

2011 07 26 iteration demoralization

See if you can guess what this will output:

    function allNames() {
      var names = [ 'dan', 'anthony', 'pavel' ];
      for (name in names) {
        console.log(name);
      }
    }

    allNames();

If you guessed this:

0
1
2

...then you are right! Congratulations!

What you might not have guessed, is what this will output:

console.log(window.name);

it's:

"2"

Iteration is assignment, and without the use of the var keyword, you're really using the global object - which in this context is the window object.

So the original function is equivalent to:

    function allNames() {
      var names = [ 'dan', 'anthony', 'pavel' ];
      for (window.name in names) {
        console.log(name);
      }
    }

By @danlash

Fork me on GitHub