Basic · 10 of 12 · 16 min read
Arrays
What each array method gives back, which ones change the array underneath you, and the handful that behave differently from how their names read.
- Arrays
An array is an ordered collection where each value has an index starting at 0. It is also an
object — which is why typeof [] === 'object', why two arrays with the same contents are never
equal, and why assigning one to a second variable does not copy it.
Almost every array question in an interview comes down to one of two things: what does this method return, and does it change the original. Learn those two columns and the rest is detail.
What each method gives back
The methods fall into four groups by what they return. Every one is shown running below, because the return value is the part that catches people out and a table alone does not make it stick.
1. Return a new array, leave the original alone
These are the safe ones. They are safe to chain, and safe to call on an array you did not create.
| Method | Returns |
|---|---|
map(fn) |
a new array, same length, each element transformed |
filter(fn) |
a new array with the elements that passed |
slice(start, end) |
a copy of a section; negative indexes count from the end |
concat(other) |
the two arrays joined into a new one |
flat(depth) |
nested arrays unwrapped, one level by default |
flatMap(fn) |
map then flat(1), for a callback that returns arrays |
toSorted(fn) / toReversed() |
newer, non-mutating versions of sort / reverse |
const nums = [1, 2, 3, 4];
console.log(nums.map((n) => n * 2)); // [2, 4, 6, 8]
console.log(nums.filter((n) => n > 2)); // [3, 4]
console.log(nums.slice(1, 3)); // [2, 3]
console.log(nums.slice(-2)); // [3, 4] — last two
console.log(nums.concat([5, 6])); // [1, 2, 3, 4, 5, 6]
console.log([1, [2, [3]]].flat()); // [1, 2, [3]] — one level
console.log([1, [2, [3]]].flat(Infinity)); // [1, 2, 3]
console.log(nums.flatMap((n) => [n, -n])); // [1, -1, 2, -2, 3, -3, 4, -4]
console.log([3, 1, 2].toSorted()); // [1, 2, 3]
console.log(nums); // [1, 2, 3, 4] — untouched by all of the above
2. Return one value, leave the original alone
The array goes in, something that is not an array comes out. This is where “I expected an array” bugs come from.
| Method | Returns |
|---|---|
find(fn) |
the first matching element, or undefined |
findIndex(fn) |
the first matching index, or -1 |
findLast(fn) / findLastIndex(fn) |
the same, searching from the end |
includes(value) |
a boolean |
indexOf(value) |
the index, or -1 |
some(fn) |
true if at least one passed |
every(fn) |
true if all passed |
reduce(fn, seed) |
whatever you accumulated — a number, an object, anything |
join(sep) |
a string |
at(i) |
the element at i; negative counts from the end |
const users = [
{ id: 1, name: 'Ana', active: true },
{ id: 2, name: 'Beto', active: false },
];
console.log(users.find((u) => u.id === 2)); // { id: 2, name: 'Beto', … }
console.log(users.findIndex((u) => u.id === 2)); // 1
console.log(users.find((u) => u.id === 9)); // undefined
console.log(users.findIndex((u) => u.id === 9)); // -1 ← not undefined
const nums = [1, 2, 3];
console.log(nums.includes(2)); // true
console.log(nums.indexOf(2)); // 1
console.log(nums.some((n) => n > 2)); // true
console.log(nums.every((n) => n > 2)); // false
console.log(nums.reduce((a, b) => a + b, 0)); // 6
console.log(nums.join('-')); // "1-2-3"
console.log(nums.at(-1)); // 3
reduce is the general one — it can build anything, including an object, which is how you group a
list:
const byActive = users.reduce((acc, user) => {
const key = user.active ? 'active' : 'inactive';
acc[key] = [...(acc[key] ?? []), user.name];
return acc;
}, {});
console.log(byActive); // { active: ['Ana'], inactive: ['Beto'] }
3. Return undefined
Only one, and it is worth its own group because people try to use its result.
| Method | Returns |
|---|---|
forEach(fn) |
undefined, always — whatever the callback returns is discarded |
const nums = [1, 2, 3];
const doubled = nums.forEach((n) => n * 2);
console.log(doubled); // undefined ← the callback's results went nowhere
// `forEach` is for side effects:
nums.forEach((n) => console.log(n)); // 1 / 2 / 3
// If you want the results, that is `map`:
console.log(nums.map((n) => n * 2)); // [2, 4, 6]
4. Change the array, and return something that is not it
These mutate. The return value is almost never what you want to chain off.
| Method | Returns | Changes the array by |
|---|---|---|
push(x) |
the new length | adding at the end |
unshift(x) |
the new length | adding at the start |
pop() |
the removed element | removing from the end |
shift() |
the removed element | removing from the start |
splice(i, n) |
an array of the removed elements | cutting out of the middle |
sort(fn) |
the same array, reordered | reordering in place |
reverse() |
the same array, reversed | reversing in place |
fill(x) |
the same array, filled | overwriting every slot |
const arr = [1, 2, 3];
console.log(arr.push(4)); // 4 ← the new length, not the array
console.log(arr.unshift(0)); // 5 ← the new length again
console.log(arr); // [0, 1, 2, 3, 4]
console.log(arr.pop()); // 4 ← the element it removed
console.log(arr.shift()); // 0
console.log(arr); // [1, 2, 3]
console.log(arr.splice(1, 1)); // [2] ← an array of what it removed
console.log(arr); // [1, 3]
console.log(arr.reverse()); // [3, 1] ← the same array, reordered
console.log([1, 2].fill(0)); // [0, 0]
The chaining trap falls straight out of that first line:
const items = [1, 2];
// Looks like "add 3 and keep going". It is not.
const wrong = items.push(3).map((n) => n * 2); // TypeError: items.push(...).map is not a function
// Append without mutating, and the chain works:
const right = [...items, 3].map((n) => n * 2);
console.log(right); // [2, 4, 6]
The pairs people mix up
slice and splice
One letter apart, and they do opposite things. slice copies a section and leaves the array alone;
splice cuts elements out in place and gives you what it removed.
const a = [1, 2, 3, 4];
console.log(a.slice(1, 3)); // [2, 3]
console.log(a); // [1, 2, 3, 4] — untouched
console.log(a.splice(1, 2)); // [2, 3] — the removed ones
console.log(a); // [1, 4] — changed
slice also accepts negative indexes, counting back from the end — a.slice(-2) is the last two
elements. splice does not read them that way.
find and filter
Same callback shape, different answers. find gives you the element and stops at the first match;
filter always walks the whole array and gives you an array.
const nums = [1, 2, 3, 4];
console.log(nums.find((n) => n > 2)); // 3
console.log(nums.filter((n) => n > 2)); // [3, 4]
console.log(nums.find((n) => n > 9)); // undefined
console.log(nums.filter((n) => n > 9)); // []
If you only need to know whether something is there, some is clearer than filter(...).length.
some and every
Both return a boolean and both stop early — in opposite directions. some stops at the first pass,
every at the first failure. The edge case is worth knowing because it surprises people:
console.log([].some((n) => n > 2)); // false
console.log([].every((n) => n > 2)); // true — vacuously true
The default sort is not numeric
sort converts every element to a string before comparing, so numbers come out in dictionary order:
console.log([10, 9, 1].sort()); // [1, 10, 9]
For numbers you have to pass a comparator. And since sort mutates, copy first unless you want the
original reordered:
const nums = [10, 9, 1];
console.log([...nums].sort((a, b) => a - b)); // [1, 9, 10]
console.log(nums); // [10, 9, 1] — the spread saved it
Newer runtimes also give you toSorted and toReversed, which are the non-mutating versions.
Copying an array
Assignment copies the reference, not the contents. Both names then point at one array:
const arr = [1, 2, 3];
const copy = arr;
copy.push(4);
console.log(arr.length); // 4 — same array
Any of these give you a genuinely separate array:
const a = [...arr];
const b = arr.slice();
const c = Array.from(arr);
All three are shallow. If the elements are objects, both arrays still point at the same objects,
and mutating one is visible through the other. structuredClone(arr) is the deep version.
Holes are not undefined
An array can have a length without having elements, and the callback-based methods skip the gaps:
console.log(new Array(3).map((_, i) => i)); // [ <3 empty items> ] — callback never ran
Two forms that do produce real elements:
console.log(Array.from({ length: 3 }, (_, i) => i)); // [0, 1, 2]
console.log([...Array(3)].map((_, i) => i)); // [0, 1, 2]
Common mistakes
Chaining off a mutating method
Mistake. const next = arr.push(item) or items.sort().map(...) on an array you did not want
reordered.
Why it fails. push returns a length, and sort reorders the original while returning the same
reference, so the “copy” you thought you made is the same array.
What to do instead. Build new arrays: [...arr, item] to append, [...arr].sort(cmp) to order.
Reaching for filter when you want one thing
Mistake. users.filter((u) => u.id === id)[0].
Why it fails. It walks the whole array to build a one-element array you immediately throw away,
and the [0] quietly becomes undefined when nothing matched.
What to do instead. users.find((u) => u.id === id) — same result, stops at the match, and says
what it means.
Forgetting that the copy is shallow
Mistake. const copy = [...items] and then editing copy[0].name.
Why it fails. The spread copied the references; copy[0] and items[0] are the same object.
What to do instead. Copy the level you are about to change — items.map((i) => ({ ...i })) — or
structuredClone for the whole structure.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
find and filter take the same kind of callback. What do they return?
A "copy" that still changes the original is one of the most common early JavaScript bugs.
This was meant to leave arr untouched. Why did arr change?
const arr = [1, 2, 3];
const copy = arr;
copy.push(4);
console.log(arr.length); // 4The mutating array methods all return something, and it is not always the array.
What does this log?
const arr = [1, 2];
console.log(arr.push(3));Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.