Arrays
A JavaScript array is an ordered, resizable list accessed by numeric index. Under the hood it is an object whose keys are integer-like strings, so it can grow, shrink, and even contain gaps.
Detailed Explanation
Coming from C or Java, you expect an array to be a fixed block of memory holding values of one type. A JavaScript array is not that. Specification-wise it is an ordinary object with a special length property and keys that look like integers. arr[0] is defined as a lookup of the property "0".
That sounds slow, and it would be, so engines cheat. V8 and SpiderMonkey store a packed array — indices 0..length-1 all present, no gaps — as a real contiguous backing store, close to a C array. You get that fast path for free as long as you keep the array dense.
Break the density and the engine falls back to dictionary mode, a hash table keyed by index. Three things trigger it: leaving a hole (arr[1000] = 1 on a 3-element array), removing an element with delete, or writing [1, , 3] with an elision. In dictionary mode every read is a hash lookup and the array is several times slower. This is the single biggest performance mistake beginners make with arrays.
A hole is not the same as undefined. A hole means the property does not exist. arr[1] returns undefined either way, but 1 in arr is false for a hole and true for a stored undefined. Older methods like forEach, map, filter, and reduce skip holes; newer ones like Array.from, spread, for...of, and includes treat them as undefined. Mixed behaviour on the same data is a bug factory, so never create holes.
delete arr[i] is always a mistake. It removes the property, leaves length unchanged, and punches a hole. Use splice(i, 1) to remove and close the gap, or filter to build a new array.
length is writable, which surprises people. Assigning a smaller number truncates destructively: arr.length = 0 is a fast way to empty an array in place. Assigning a larger number creates holes.
Cost of the main operations
| Operation | Cost | Note |
|---|---|---|
arr[i] read or write | O(1) | on a packed array |
push / pop | O(1) amortised | occasional reallocation |
shift / unshift | O(n) | every element reindexes |
splice(i, k) | O(n − i) | tail shifts |
indexOf / includes / find | O(n) | linear scan |
sort | O(n log n) | comparison sort |
slice / concat / spread | O(n) | copies |
Two sort facts that show up in interviews. First, the default comparator converts elements to strings, so [10, 9, 1].sort() gives [1, 10, 9]. Always pass (a, b) => a - b for numbers. Second, sort has been required to be stable since ES2019: elements the comparator calls equal keep their original relative order. Before that, V8 used an unstable quicksort for arrays longer than 10.
Reach for an array whenever order matters and you look things up by position. If you look things up by key, use a Map. If you need fixed-width binary numbers, use a typed array.
Code Examples
Holes are not `undefined`, and methods disagree about them.
// Holes are not `undefined`, and methods disagree about them.
const withHole = [1, , 3]; // the elision creates a hole at index 1
const withUndefined = [1, undefined, 3];
console.log(withHole.length, withUndefined.length); // => 3 3
console.log(1 in withHole, 1 in withUndefined); // => false true
console.log(Object.keys(withHole)); // => [ '0', '2' ] the "1" key does not exist
let visited = 0;
withHole.forEach(() => visited++);
console.log(visited); // => 2 forEach skips the hole
console.log([...withHole]); // => [ 1, undefined, 3 ] spread fills it in
// `delete` punches a hole and keeps length. Use splice instead.
const tasks = ["write", "review", "ship"];
delete tasks[1];
console.log(tasks.length, 1 in tasks); // => 3 false
const clean = ["write", "review", "ship"];
clean.splice(1, 1); // remove 1 element at index 1 and close the gap
console.log(clean); // => [ 'write', 'ship' ]
// `length` is writable, and shrinking it discards elements.
clean.length = 0;
console.log(clean); // => []Default sort is lexicographic, not numeric.
// Default sort is lexicographic, not numeric.
console.log([10, 9, 1].sort()); // => [ 1, 10, 9 ]
console.log([10, 9, 1].sort((a, b) => a - b)); // => [ 1, 9, 10 ]
// Stable since ES2019: equal keys keep their input order.
const players = [
{ name: "Ada", team: "red" },
{ name: "Bram", team: "blue" },
{ name: "Cleo", team: "red" },
];
players.sort((x, y) => x.team.localeCompare(y.team));
console.log(players.map((p) => p.name)); // => [ 'Bram', 'Ada', 'Cleo' ]
// Building a dense array of a known size, with no holes.
const zeros = Array.from({ length: 4 }, () => 0);
console.log(zeros); // => [ 0, 0, 0, 0 ]
console.log(new Array(4)); // => [ <4 empty items> ] all holes, avoidCommon Gotchas
Default `sort` is string-based
`[10, 9].sort()` returns `[10, 9]` because `"10" < "9"` as text. Numeric data needs an explicit `(a, b) => a - b` comparator.
`delete arr[i]` creates a hole
it does not shorten the array and it can push the engine out of its fast packed representation. Use `splice` or `filter`.
Sparse arrays deoptimise
assigning a far-off index such as `arr[100000] = 1` switches the array to a hash-table layout and slows every subsequent access.
`typeof []` is `"object"`
arrays are objects, so use `Array.isArray(value)` to test for one.