JavaScript "for-in" Caveat With Arrays

• 1 min read

Don’t use for (var i in myArray) ever!

Apparently JavaScript for-in loops always convert the key to a String type. This has caused me troubles multiple times in the past and I would like to share my experiences with the world.

var myArray = [ 'foo', 'bar' ];

for (var i in myArray) {
  if (i === 0) {
    console.log('First!');
  } else {
    console.log('Not first :(');
  }
}

/**
 * Output:
 *
 * Not first :(
 * Not first :(
 *
 */

Confusing right? “First!” is never outputted because i is always a String, which is never strictly equal (===) to a Number. So, in summary, whenever you want to iterate over an array, it’s usually best to stick with the long form version:

var myArray = [ 'foo', 'bar' ];

for (var i=0; i<myArray.length; i++) {
  if (i === 0) {
    console.log('First!');
  } else {
    console.log('Not first :(');
  }
}

/**
 * Output:
 *
 * First!
 * Not first :(
 *
 */

This will always produce the correct result.

Be the first to cheers
Now look what you've done 🌋
Stop clicking and run for your life! 😱
Uh oh, I don't think the system can't handle it! 🔥
Stop it, you're too kind 😄
Thanks for the love! ❤️
Thanks, glad you enjoyed it! Care to share?
Hacker News Reddit

×

Recommended Posts ✍🏻

See All »
• 3 min read
✨ HTML Share Buttons
Read Post »
• 8 min read
🚜 A Simple Web Scraper in Go
Read Post »
• 2 min read
👨🏼‍💻 Going Indie, Again
Read Post »