Immutable Adding Elements to an Array in JavaScript
Let's now learn how to perform immutable addition of elements to an array. For example, let's say we have some array:
let arr = [1, 2, 3, 4, 5];
Let's add a new element to it. According to our approach, we must make a copy of the array and add the new element to this copy. Let's do this:
let copy = Object.assign([], arr);
copy.push(6);
let res = copy;
And now let's use the second approach with destructuring:
let res = [...arr, 6];
Create a button that, when clicked, will perform an immutable addition of a new element to the array.