Arrays and Iteration
Spread Append
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
basestarts as[1, 2, 3].extrastarts as5.[...base, extra]copies the base values into a new array.- The new
grownarray becomes[1, 2, 3, 5]. baseis unchanged, sobaseSizestays3. | 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.