// non-mutating methods array.map() array.slice() array.concat() [...array] // spread operator array.filter() // mutating methods array.push() array.unshift() array.pop() array.shift() array.splice()
To keep the integrity of the original array, you need to use .slice()
to the original array to make exact value copy of it
const arr = [1, 2, 3]; // immutable function immutableRemoveElBack(arr) { let nArr = arr.slice(0, arr.length-1); return nArr; } // instantiate deep copy const newArr = immutableRemoveElBack(arr); console.log(arr); // [1, 2, 3] untouched console.log(newArr); // [1, 2] deep copy
// original const arr = [1, 2, 3]; function mutableRemoveElBack(arr) { let nArr = arr; nArr.pop(); return nArr; } const newArr = mutableRemoveElBack(arr); console.log(arr); // [1, 2] modified console.log(newArr); // [1, 2]