Build a new array instead of changing the old one.

copy-array Immutable updates create a new value. Array spread is a common way to copy existing values and add one more item.

Copying Arrays

extra
copy_array.js
Replay: real traced execution (multi-file project)
const extra = 4;
const copied = [...[1, 2, 3], extra].join(",");
const count = copied.split(",").length;

console.log("copied=" + copied);
console.log("count=" + count);
const extra = 6;
const copied = [...[1, 2, 3], extra].join(",");
const count = copied.split(",").length;

console.log("copied=" + copied);
console.log("count=" + count);
const extra = 8;
const copied = [...[1, 2, 3], extra].join(",");
const count = copied.split(",").length;

console.log("copied=" + copied);
console.log("count=" + count);
  1. extra ← 4, copied ← 1,2,3,4, count ← 4

    1const extra→ 4 = 4; //@extra=6, 82const copied→ 1,2,3,4 = [...[1, 2, 3], extra4].join(",");3const count→ 4 = copied1,2,3,4.split(",").length;45console.log("copied=" + copied1,2,3,4);6console.log("count=" + count4);
    outputcopied=1,2,3,4
    count=4
  1. extra ← 6, copied ← 1,2,3,6, count ← 4

    1const extra→ 6 = 6;2const copied→ 1,2,3,6 = [...[1, 2, 3], extra6].join(",");3const count→ 4 = copied1,2,3,6.split(",").length;45console.log("copied=" + copied1,2,3,6);6console.log("count=" + count4);
    outputcopied=1,2,3,6
    count=4
  1. extra ← 8, copied ← 1,2,3,8, count ← 4

    1const extra→ 8 = 8;2const copied→ 1,2,3,8 = [...[1, 2, 3], extra8].join(",");3const count→ 4 = copied1,2,3,8.split(",").length;45console.log("copied=" + copied1,2,3,8);6console.log("count=" + count4);
    outputcopied=1,2,3,8
    count=4