Add an element by building a new array.

Spread Append

spread_append.js
const extra = 5;
const base = [1, 2, 3];
const grown = [...base, extra];

console.log("base=" + base.join(","));
console.log("grown=" + grown.join(","));
console.log("baseSize=" + base.length);

Follow the Spread

  1. base starts as [1, 2, 3].
  2. extra starts as 5.
  3. [...base, extra] copies the base values into a new array.
  4. The new grown array becomes [1, 2, 3, 5].
  5. base is unchanged, so baseSize stays 3. | value | output text | | --- | --- | | base | base=1,2,3 | | grown | grown=1,2,3,5 | | base.length | baseSize=3 |
spread-append The spread `...` copies an array's elements into a new array. Appending this way leaves the original array unchanged.

Exercise: spread_append.js

Reproduce base=1,2,3, grown=1,2,3,5, and baseSize=3, then use the pinned extra variants 9 and 1 to predict grown=1,2,3,9 and grown=1,2,3,1 while base stays unchanged.