After this lesson you can grow and shrink an array, cut pieces out of it, and look things up in it. You will also know which methods quietly change your array and which hand you a new one, a distinction that causes many bugs.
Adding and removing at the ends
Four methods work at the edges of an array. Think of the end as the "back" and the start as the "front".
| Method | Where | What it does | Returns |
|---|---|---|---|
push(x) |
end | adds an item | the new length |
pop() |
end | removes the last item | that item |
unshift(x) |
start | adds an item | the new length |
shift() |
start | removes the first item | that item |
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const queue = ["b", "c"];
queue.push("d"); // b c d
queue.unshift("a"); // a b c d
log(queue.join(" "));
const last = queue.pop(); // removes d
const first = queue.shift(); // removes a
log("removed:", first, last);
log("left:", queue.join(" "));
</script>All four mutate the array: the original changes. That is why they work on a const array. push accepts several items at once, as in list.push(1, 2, 3). Items taken from the end with pop are fast; shift and unshift have to move every other item, which matters only for very large arrays.
splice: remove or insert anywhere
splice(start, deleteCount, ...itemsToInsert) is the Swiss army knife. It changes the array and returns an array of whatever it removed.
const letters = ["a", "b", "c", "d", "e"];
const removed = letters.splice(1, 2); // from index 1, remove 2 items
console.log(removed); // [ 'b', 'c' ]
console.log(letters); // [ 'a', 'd', 'e' ]
letters.splice(1, 0, "x", "y"); // at index 1, remove 0, insert x and y
console.log(letters); // [ 'a', 'x', 'y', 'd', 'e' ]Use it when you know a position. Its argument order (start, how many to delete, then new items) takes a while to remember, so keep this lesson handy.
slice: copy a section
slice(start, end) returns a new array with the items from start up to, but not including, end. The original is untouched. Negative numbers count from the end.
const nums = [10, 20, 30, 40, 50];
console.log(nums.slice(1, 3)); // [ 20, 30 ]
console.log(nums.slice(-2)); // [ 40, 50 ]
console.log(nums.slice()); // [ 10, 20, 30, 40, 50 ] (a shallow copy)
console.log(nums.length); // 5, unchangedThe names are confusingly close. A way to remember: slice is a clean cut for a copy, while splice is surgery on the array itself.
Searching
Checking for a value you already know:
const colours = ["red", "green", "blue", "green"];
console.log(colours.includes("blue")); // true
console.log(colours.indexOf("green")); // 1, the first match
console.log(colours.lastIndexOf("green")); // 3
console.log(colours.indexOf("pink")); // -1, not foundPrefer includes when you only want a yes or no, because if (arr.indexOf(x)) is a trap: the index 0 is falsy, so an item in the first position looks like a failure.
Searching with a test, where you give a function that returns true for the item you want:
const products = [
{ name: "pen", price: 2 },
{ name: "book", price: 12 },
{ name: "bag", price: 30 },
];
const firstExpensive = products.find(p => p.price > 10);
console.log(firstExpensive); // { name: 'book', price: 12 }
console.log(products.findIndex(p => p.name === "bag")); // 2
console.log(products.find(p => p.price > 100)); // undefined
console.log(products.some(p => p.price > 20)); // true
console.log(products.every(p => p.price > 1)); // truefind gives the item, findIndex gives its position, some asks whether at least one item passes, and every asks whether all do. findLast and findLastIndex do the same from the end, and are part of modern JavaScript (ES2023).
Mutating or not?
A useful habit is to know, for every method, whether it changes the array.
- Changes the original:
push,pop,shift,unshift,splice,sort,reverse,fill. - Returns something new:
slice,concat,map,filter,join,includes,find.
ES2023 added copying versions of several mutating methods: toSpliced, toSorted, toReversed and with. For example nums.with(1, 99) returns a new array with index 1 replaced and leaves nums alone. They are in current browsers and Node 20 and later; check your target browsers if you support very old ones.
Why care? In frameworks such as React you must not mutate state, so the copying style matters. Even in plain scripts, an unexpected change to a shared array is hard to track down. See arrays for why two names can share one array.
Combining arrays
concat or spread joins arrays into a new one:
const a = [1, 2];
const b = [3, 4];
console.log([...a, ...b]); // [ 1, 2, 3, 4 ]
console.log(a.concat(b, [5])); // [ 1, 2, 3, 4, 5 ]Common mistakes
- Using the return value of
pushas the array.const list = items.push(5)stores the new length, a number. - Mixing up
sliceandsplice. One copies, the other changes the array. - Writing
if (arr.indexOf(x)). It is false for position 0 and true for -1. Compare with-1explicitly or useincludes. - Removing items inside a loop over the same array. Items shift under you and some get skipped. Loop backwards, or build a new array with
filter. - Expecting
findto returnfalse. It returnsundefinedwhen nothing matches.
Exercise
Start with const tasks = ["wash", "cook", "study"]. Add "sleep" at the end, put "wake up" at the start, remove "cook" using indexOf and splice, and show the final list. Then say whether tasks.includes("cook") is true.
Show one possible answer
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const tasks = ["wash", "cook", "study"];
tasks.push("sleep");
tasks.unshift("wake up");
const i = tasks.indexOf("cook");
if (i !== -1) tasks.splice(i, 1);
log(tasks.join(", "));
log("includes cook?", tasks.includes("cook"));
</script>Next: map, filter and reduce.
Key points
- push and pop work at the end of an array; unshift and shift work at the start. All four change the array.
- splice removes or inserts items at any position and changes the array; slice copies a section and does not.
- includes answers yes or no, indexOf gives a position or -1, find returns the first matching item.
- findIndex and findLast, findLastIndex search with a test function instead of a fixed value.
- Know which methods mutate the array. Newer toSorted, toSpliced and with return changed copies instead.