Search code examples
javascriptarraysfor-in-loop

Pushing to array of for-in loop to extend the number of iterations of that for-in loop


Consider this in Javascript:

var words = ['hello,','how','are'];
for(var word in words) {
    console.log(words[word]);
    if (words[word] == 'are') {
        words.push('you');
    }
}

It outputs:

hello,
how
are

My expectation is that it would output this to the console:

hello,
how
are
you

So, it appears that the number of iterations is set by the length of words at the start of the loop, and it cannot update that number as the length of words changes through the duration of the loop. Can anyone think of another way to do this?


Solution

  • You should not use for..in to iterate over an array. Use the new for..of if it's available or keep track of an index to iterate. Both will iterate online (i.e. over items that are added). .forEach does not iterate online.

    var words = ['hello,','how','are'];
    for (var i = 0; i < words.length; i++) {
        console.log(words[i]);
        if (words[i] == 'are') {
            words.push('you');
        }
    }
    
    // ES6
    let words = ['hello,','how','are'];
    for (let word of words) {
        console.log(word);
        if (word == 'are') {
            words.push('you');
        }
    }