DevPath · Learn to code ESPTEN

Arrays and their methods

Adding, removing and slicing

Methods to modify arrays

Here comes the module's ⚠️ CLASSIC TRAP: some methods mutate the original array (they change it in place) and others return a copy without touching it. Mixing them up is the source of very sneaky bugs. In this lesson, push, pop, shift, unshift and splice do mutate; slice doesn't. Keep it in mind.

Adding and removing from the ends

const stack = [1, 2, 3];
stack.push(4);    // adds at the end -> [1, 2, 3, 4]
stack.pop();      // removes from the end -> [1, 2, 3]
stack.unshift(0); // adds at the start -> [0, 1, 2, 3]
stack.shift();    // removes from the start -> [1, 2, 3]
Method What it does Returns
push adds at the end the new length
pop removes from the end the removed element
unshift adds at the start the new length
shift removes from the start the removed element

slice: copy a chunk (doesn't modify)

slice(start, end) returns a copy from start up to just before end. It does not alter the original array.

const letters = ["a", "b", "c", "d"];
console.log(letters.slice(1, 3)); // ["b", "c"]
console.log(letters);             // intact: ["a","b","c","d"]

splice: insert/remove (does modify)

splice(start, howManyToDelete, ...newItems) modifies the array in place:

const list = ["a", "b", "c"];
list.splice(1, 1);          // deletes 1 from index 1 -> ["a", "c"]
list.splice(1, 0, "x");     // inserts "x" at index 1 -> ["a", "x", "c"]

Mnemonic rule: slice slim (gentle, copies); splice Sparta (rough, modifies).

Examples

push and pop on a stack

const tasks = [];
tasks.push("wash");
tasks.push("cook");
tasks.push("study");
console.log(tasks);        // ["wash", "cook", "study"]
const last = tasks.pop();
console.log(last, tasks); // "study" ["wash", "cook"]
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Creating arrays, indices and lengthSearching for elements →