Arrays
An ordered list of values, stored in a single variable.
What is it?
Often you have many values to track: a list of names, scores or products. Instead of a separate variable for each, use an array: one container holding an ordered list of values, each reachable by its position (its "index").
Indexes start at 0, so the first item is at 0, the second at 1, and so on.
Explain like I'm 10
An array is like a row of numbered lockers. Locker 0 holds the first item, locker 1 the second, and so on. If you know the number, you can open any locker directly.
Examples
Creating and using an array
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // "apple"
console.log(fruits.length); // 3
fruits.push("date"); // adds to the end
fruits.pop(); // removes the last itemLooping over an array
const scores = [10, 20, 30];
scores.forEach((score) => {
console.log(score);
});How it works
An array stores its items in order and tracks how many there are (its length). fruits[0] jumps straight to the item at position 0 without checking the others.
Why does it exist?
Almost every program handles collections: a list of users, a shopping cart, search results. Arrays are the built-in way to store, access and process ordered groups of data.
When to use it
Use an array for several related values with a natural order: to-dos, scores, search results. If you're naming variables item1, item2, item3, you want an array.
When not to use it
If the values are named attributes of one thing (a person's name, age and email), use an object. If you need fast lookups by a unique key instead of by position, a Map or object beats searching an array.
Common mistakes
Forgetting that array indexes start at 0, not 1.
Trying to access an index that doesn't exist (returns
undefinedinstead of an error).Using
for...inon an array instead offor...ofor.forEach(), which can produce unexpected results.
Practice exercises
- Easy:
Create an array of 5 numbers and log the third one.
- Medium:
Use
.map()to create a new array where every number is doubled. - Hard:
Use
.filter()and.reduce()together to sum only the even numbers in an array.
Interview questions
What is an array in JavaScript?
An ordered list of values in a single variable. Each value is accessed by its numeric position (index), not a name.
Why do array indexes start at 0 instead of 1?
An index is an offset from the start, not a count. The first item is 0 steps from the start, the second is 1 step away, and so on.
Does `array.length` update automatically as you add or remove items?
Yes. length is kept in sync after push, pop, splice, or a direct assignment like arr[10] = "x".
What's the difference between `push()`/`pop()` and `unshift()`/`shift()`?
push/pop add and remove at the end; unshift/shift do it at the start. Changing the front means re-indexing every other element, so unshift/shift are slower on large arrays.
What does accessing an index beyond an array's length return?
undefined, not an error. arr[i] is a property lookup, and a missing key gives undefined.
What's the difference between `slice()` and `splice()`?
slice(start, end) returns a new array with a copied range and leaves the original alone. splice(start, deleteCount, ...items) changes the original in place, removing and/or inserting items, and returns the removed ones.
What does this log? `const a = [1, 2, 3]; const b = a; b.push(4); console.log(a);`
[1, 2, 3, 4]. b = a copies the reference, not the array, so both point to the same array and a change through one shows through the other.
Why does `typeof []` return `"object"` instead of `"array"`?
There's no separate array type. An array is a special object with numeric keys and an auto-updating length, so typeof reports "object".
How do you reliably check whether a value is an array?
Array.isArray(value). typeof can't tell an array from a plain object, but this check inspects the value's internal class.
What does this log, and why? `console.log([10, 1, 2].sort());`
[1, 10, 2]. Without a comparator, sort() turns elements into strings and compares them alphabetically, so "10" comes before "2". For numbers, pass a comparator like (a, b) => a - b.
Does `.sort()` mutate the original array?
Yes. sort() (like reverse(), splice() and fill()) reorders in place and returns the same array, not a new one.
How do you copy an array without mutating the original?
Spread it ([...arr]), call arr.slice() with no arguments, or use Array.from(arr). All three create a new array, but only one level deep.
What does this log? `const original = [{ id: 1 }]; const copy = [...original]; copy[0].id = 2; console.log(original[0].id);`
2. Spread copies only the top-level slots. Both arrays hold the same object at index 0, so changing it through copy shows through original.
What happens when you set `array.length = 0`?
It empties the array in place. This keeps the same reference, which matters if other code holds that array.
What is a 'sparse' array, and how do you accidentally create one?
An array with gaps: missing indexes, not actual undefined values. [1, , 3] and new Array(3) both create one. length counts the gaps, but some iteration methods treat them differently from real values.
What does this log? `const arr = [1, , 3]; console.log(arr.length); arr.forEach((n) => console.log(n));`
3 (length counts the hole), then 1 and 3. forEach (like map and filter) skips empty slots instead of passing undefined.
What does the `delete` operator do to an array element, and why is it rarely what you want?
delete arr[1] removes the value but leaves a hole: length stays the same and later items don't shift down. You almost always want splice(1, 1).
How does `for...in` differ from `for...of` when looping over an array?
for...in loops over enumerable keys as strings, including any non-index properties added to the array, in no guaranteed order. for...of loops over the values in index order, which is almost always what you want.
What does this log? `console.log([NaN].indexOf(NaN)); console.log([NaN].includes(NaN));`
-1 then true. indexOf uses strict equality and NaN !== NaN, so it never finds it. includes uses SameValueZero, which treats NaN as equal to itself.
How do you convert an array-like object, like `arguments`, into a real array?
Array.from(arguments) or [...arguments]. Both build a real array with array methods, which the array-like (just indexes and length) lacks.
What's the difference between `Array.from()` and `Array.of()`?
Array.from(source, mapFn?) builds an array from an iterable or array-like, optionally mapping each item. Array.of(...items) builds an array from its arguments, avoiding the new Array(n) ambiguity.
What's confusing about `new Array(7)`?
With one numeric argument, it creates an empty sparse array of length 7, not an array containing 7. Use Array.of(7) or [7] instead.
What's the difference between `.flat()` and `.flatMap()`?
flat(depth) flattens nested arrays by the given depth (default 1). flatMap(fn) maps each item and flattens one level in a single pass, more efficient than .map().flat().
How do you access the last item of an array?
arr[arr.length - 1], or more directly arr.at(-1), since .at() accepts negative indexes counted from the end.
What does this log? `function addItem(arr) { arr.push("new"); } const list = ["a", "b"]; addItem(list); console.log(list);`
["a", "b", "new"]. The function gets a copy of the reference, so arr points to the same array as list, and changes through it are visible to the caller.
What does this log? `function replace(arr) { arr = ["x", "y"]; } const list = ["a", "b"]; replace(list); console.log(list);`
["a", "b"], unchanged. arr = ["x", "y"] only points the local parameter at a new array. The reference was passed by value, so list is unaffected.
Why does `[] === []` evaluate to `false`?
=== on arrays (and objects) compares references, not contents. Two array literals are two separate objects, even with identical elements.
How would you compare two arrays for equality by content?
There's no built-in deep check. A shallow one is a.length === b.length && a.every((v, i) => v === b[i]). JSON.stringify(a) === JSON.stringify(b) works for simple data but breaks with nested objects, undefined, functions or different key order.
Why are `push`/`pop` generally faster than `unshift`/`shift`?
push/pop only touch the end: O(1). unshift/shift must move every other element's index by one: O(n).
What does this log, and why? `const arr = [1, 2, 3]; arr.forEach((item, i) => { if (i === 0) arr.splice(1, 1); console.log(item); });`
1 then 3; 2 is skipped. Removing index 1 moves 3 into that slot, and forEach moves on to index 1, which now holds 3. Changing an array while looping over it is a common source of subtle bugs.
What does this log? `const [a = 5] = [null];`
a is null, not 5. A destructuring default applies only when the value is undefined, not for other falsy values like null, 0 or "".
How would you remove duplicate values from an array of numbers or strings in one line?
[...new Set(array)]. A Set keeps only unique values (by SameValueZero), so spreading it back gives the array without duplicates.
When would you reach for `.find()` instead of `.filter()[0]`?
find() stops at the first match and returns it (or undefined). filter() scans the whole array and builds a new one, only for you to throw away all but index 0.
Why is chaining several array methods like `.filter().map().reduce()` sometimes worth avoiding on very large arrays?
Each call is a full pass that creates an intermediate array. One .reduce() (or a plain loop) does it in a single pass, trading some readability for fewer allocations.