Skip to content

Javascript: add value to array while looping that will then also be included in the loop

Sorry if this is a dupplicate, can’t seem to find it.

var a = [1,2,3,4];
  if(value == 1) a.push(5);

I wonder if there is a way (any sort of loop or datatype) so that this will ouput 1 2 3 4 5 during the loop (or in any order, as long as all the 5 numbers are in there)



Using Array.prototype.forEach() will not apply the callback to elements that are appended to, or removed from, the array during execution. From the specification:

The range of elements processed by forEach is set before the first call to callbackfn. Elements which are appended to the array after the call to forEach begins will not be visited by callbackfn.

You can, however, use a standard for loop with the conditional checking the current length of the array during each iteration:

for (var i = 0; i < a.length; i++) {
    if (a[i] == 1) a.push(5);