How can the following operation be done without mutating the array:
let array = ['item1'];
console.log(array); // ['item1']
array[2] = 'item2'; // array is mutated
console.log(array); // ['item1', undefined, 'item2']
In the above code, array
variable is mutated. How can I perform the same operation without mutating the array?
You can use Object.assign(target, source1, source2, /* …, */ sourceN)
:
Object.assign([], array, {2: newItem});