Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.2 — Adding, Removing and Changing
JavaScript · Example 3 of 3 ES2023+

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.

01

Start with const tasks = ["wash", "cook"];. Add "shop" at the start and "sleep" at the end, then remove "cook" with splice. Print the array.

02

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

01

What do push, pop, shift and unshift return?

02

Explain the arguments and return value of splice.

03

What is the difference between a mutating and a non-mutating array method, and why does it matter?

04

Why is shift slower than pop on a large array?

Mutating vs non-mutating ES2023+

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
[]