codecks.

Arrays & objects · Output question

JavaScript map when the source array grows

A callback appends an element while map is running. Predict how many source elements the callbacks visit.

const values = [1, 2];
const twice = values.map((value, index) => {
  if (index === 0) values.push(3);
  return value * 2;
});
console.log(twice.join(","));
console.log(values.join(","));

What gets logged?

Choose an output before opening the walkthrough, or check your answer in practice mode.

  1. 2,4,6
    1,2,3
  2. 2,4
    1,2
  3. 2,4,6
    1,2
  4. 2,4
    1,2,3
Reveal the answer and execution trace
2,4
1,2,3

map captures the array length before iteration. The appended element is outside that original range.

  1. Line 2. map starts with an iteration length of two.
  2. Line 3. The first callback appends 3 to values.
  3. Line 4. The callbacks for original indexes 0 and 1 return 2 and 4.
  4. Line 6. The mapped array has two entries.
  5. Line 7. The source array was mutated and has three entries.

Reference: Array map on MDN.