push / pop
Add or remove at the end, mutating the array.
Array methods let you add, remove, copy, join and inspect list data. The key is knowing which methods mutate.
const tags = ["html", "css"];
tags.push("javascript");
const preview = tags.slice(0, 2);
Arrays & Collections
Some array methods change the original array. push, pop, shift, unshift, reverse, sort and splice mutate.
Other methods return a new value or new array. slice, concat, includes and join leave the original array alone.
Modern JavaScript also includes non-mutating alternatives such as toSorted, toReversed and toSpliced in supported runtimes.
Add or remove at the end, mutating the array.
Remove or add at the start, mutating the array.
Copy a section without mutating.
Remove or insert items by mutating the original array.
Examples
const currentTags = ["html", "css"]; const nextTags = [...currentTags, "javascript"]; console.log(currentTags); console.log(nextTags);
const currentTags = ["html", "css"];
const nextTags = currentTags;
nextTags.push("javascript");
// currentTags changed too.
Code patterns
These are the patterns developers search for constantly: reading items, copying arrays, choosing map/filter/reduce, sorting with a comparator, destructuring and using Set or Map.
Add one item to the end.
const tags = ["html", "css"];
tags.push("javascript");
console.log(tags);
Copy part of an array without changing it.
const tags = ["html", "css", "javascript"]; const firstTwo = tags.slice(0, 2);
Check whether an array contains a value.
const tags = ["html", "css"];
console.log(tags.includes("css"));
Turn array items into a string.
const tags = ["html", "css", "javascript"];
console.log(tags.join(", "));
Rules that matter
Arrays and collections are not just storage. They describe whether the code is selecting, transforming, grouping, counting, sorting or enforcing uniqueness.
push, pop, shift, unshift, sort, reverse and splice change the array.
slice is a safe way to copy a section.
It reads better than indexOf for simple checks.
It is clearer than manual concatenation.
It creates a new array for state-like updates.
Mutation is not always wrong, but it should be obvious.
Production thinking
Many array bugs are not syntax bugs. They happen because one part of the code changes a list another part still expects to be stable.
Array methods often update visible list content. Predictable updates prevent duplicate or missing items in the rendered UI.
Production code should be consistent about mutation, especially in shared state and rendering code.
Lists of links or content blocks should be assembled predictably without accidental mutation.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
A collection method should tell the reader what kind of operation is happening before they read the callback body.