I found about JavaScript array operations Unshift, shift, push, pop
However all these operations mutate the array.
Is there a way I could use these functions without causing mutation on the original data?
Somehow I feel that reading the data should not cause mutation.
Steps : Create the clone of the array using the spread operator or slice method. apply the splice method on the cloned array and return the extracted array.
Consider a common array mutation: push() . The push() method changes the original array by adding an item to the end. When you add an item, you're mutating the original array.
Array Mutations in JavaScript. Arrays in JavaScript are just objects, which means they can be mutated. In fact, many of the built-in array methods will mutate the array itself. This can mean the golden rule from above gets broken, just by using one of the built-in methods.
You can use:
var head = arr[0]; var tail = arr.slice(1);
Or in ES6:
const [head, ...tail] = arr;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With