Mutating vs non-mutating
with and toSpliced are ES2023. The original is untouched by all four copying methods. delete leaves a hole; length = 0 empties the array for everyone who holds it.
push/pop work at the end of an array, unshift/shift at the start, and splice anywhere in the middle; all of them change (mutate) the original array, while methods like slice, concat, with and toSpliced leave it alone and return a new one.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Start with const tasks = ["wash", "cook"];. Add "shop" at the start and "sleep" at the end, then remove "cook" with splice. Print the array.
Write a function removeAt(arr, i) that returns a new array without the item at index i and doesn't change arr.
Explain it without notes
What do push, pop, shift and unshift return?
Explain the arguments and return value of splice.
What is the difference between a mutating and a non-mutating array method, and why does it matter?
Why is shift slower than pop on a large array?
Console
(nothing was printed)Expected console output
[ 3, 1, 2 ]
[ 3, 1 ] [ 3, 1, 2, 4, 5 ] [ 99, 1, 2 ] [ 1, 2 ]
[ 'a', <empty>, 'c' ] 3
[]