we don’t change the original array, we deep copy the array, then update the copy.
constarr=[1,2,3];// add to the first or the end of an arrayconstnewArr=[...arr,4]/* OR */[4,...arr];// add at a specific positionconstx=arr.indexOf(2);constnewArr[...arr.slice(0,x),4,...arr.slice(x)];// [1,4,2,3]// removing a specific elementconstnewArr=arr.filter(e=>e!==2);// [1,3];// updatingconstnewArr=arr.map(e=>{if(e===2){returne=20}else{returne}});// [ 1,20,3]constnewArr=arr.map(e=>e===2?20:e);// [1,20,3]// arr.map() will create a new copy, arr.forEach() will update the original array.
- if the array contains objects, u need to deep copy them to comply with the immutabilty princible.