for … in loop with string array outputs indices

When I write some javascript such as this:

var words = ['word1', 'word2', 'word3']

for (word in words) {
    console.log(word)
}

The resulting output is the numeric indices of the respective word. I did some searching on Google and I couldn't find the exact reason for this behavior. I'm guessing that this is completely expected behavior but I would like to know the reason why.

Thanks!

Answers:

Answer

Why is nobody providing the correct answer? You NEVER iterate arrays with a for/in loop - that is only for iterating plain objects and their keys, not for iterating the items in an array.

You iterate arrays for a for loop like this:

var words = ['word1', 'word2', 'word3'];

for (var i = 0, len = words.length; i < len; i++) {
    // here words[i] is the array element
}

Or, in a modern browser, you can use the .forEach() method of arrays:

var words = ['word1', 'word2', 'word3'];

words.forEach(function(value, index, array) {
    // here value is the array element being iterated
});

See here at MDN for more info on .forEach().

ndp's reference to this post shows some good examples of things that can go wrong using for/in with arrays. You can make it works sometimes, but it is not the smart way to write Javascript array iteration.


Or, in more modern times, you can use the ES6 for/of construct which is specially built for iterating an iterable (an array is an iterable):

var words = ['word1', 'word2', 'word3'];

for (const w of words) {
    console.log(w);
}

Or, if you want both the value and the index, you can do this:

var words = ['word1', 'word2', 'word3'];

for (const [index, w] of words.entries()) {
    console.log(index, ": ", w);
}

There are several advantages of for/of over .forEach(). To start with, you have more loop control as you can use break, continue, return to control the loop flow which .forEach() does not give you. In addition, there's no additional overhead for a callback function so, in some environments, it can be faster.

Answer
  1. for..in is used to iterate over the properties of a javascript object.
  2. Think of an array as a javascript object with indexes as properties.
Answer

For ... in is intended for objects -- see this question. Apparently it can (and is) used for arrays, but this has a few risks you may not want.

Answer

As the other answers correctly point out, for...in is not for iterating over arrays. A better option is now available in newer JavaScript engines and transpilers like TypeScript with for...of:

var words = ['word1', 'word2', 'word3']

for (word of words) {
    console.log(word)
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.