JavaScript Array Elements: Indexes, length, at(), Sparse Arrays, Adding and Removing
Reading and writing array elements, why indexes are really property names, at() with negative indexes, how length grows and truncates, sparse arrays and holes (and how each method treats them), adding and removing elements, delete vs splice, emptying an array, and arrays of arrays.
kvi5hnuCode Sprout team member6 min readOn this page
The previous article created arrays. This one is about what's inside them: how indexes work, what length really means, and the strange but important topic of sparse arrays. Several common interview questions ("how do you empty an array?", "what does delete arr[i] do?") come from here.
Reading and writing elements
Use square brackets with an index. Any expression that evaluates to a non-negative integer works, and writing to an index that doesn't exist yet creates the element:
const queue = ["ana"];
queue[1] = "bo";
const next = 2;
queue[next] = "cy";
console.log(queue[0], queue[queue.length - 1], queue.length);
ana cy 3
Reading an index that doesn't exist doesn't throw: arrays have no "index out of bounds" error. You get undefined, just like a missing object property:
const pair = [true, false];
console.log(pair[2], pair[-1], pair[100]);
undefined undefined undefined
That undefined tends to cause a TypeError or NaN later, far from the real mistake. Check index < arr.length when you're not sure.
Indexes are property names
Arrays are objects (article 54), and an index is simply a property name that happens to be a canonical non-negative integer string such as "0" or "42". JavaScript converts the number you write to a string, as with any object key (article 47):
const tags = ["x", "y"];
tags["1"] = "Y"; // the string "1" is index 1
tags[1.0] = "Y!"; // 1.0 is the number 1: index 1 again
tags[-1] = "minus"; // "-1" is not an index: an ordinary property
tags[1.5] = "half"; // "1.5" is not an index either
tags.label = "meta"; // a named property
console.log(tags, tags.length);
[ 'x', 'Y!', '-1': 'minus', '1.5': 'half', label: 'meta' ] 2
Only real indexes (integers from 0 to 2³² − 2) count as elements and affect length. Everything else is an ordinary property, which for...of, map and other array methods ignore. In particular, arr[-1] is not the last element, unlike in Python.
at(): indexes from the end
arr.at(index) (ES2022) accepts negative indexes, counting back from the end: -1 is the last element, -2 the one before it:
const scores = [10, 20, 30, 40];
console.log(scores.at(0), scores.at(-1), scores.at(-2), scores.at(10));
console.log(scores[scores.length - 1]); // the old way to get the last element
console.log("hello".at(-1)); // strings and typed arrays have at() too
10 40 30 undefined
40
o
Use at(-1) for "last element"; it's shorter and harder to get wrong than arr[arr.length - 1].
length
For an ordinary (dense) array, length is the number of elements. More precisely, length is always one more than the highest index, and JavaScript keeps this true automatically in both directions:

- Writing at an index ≥ length increases
lengthtoindex + 1. - Setting
lengthsmaller deletes every element at or above the new length.
const letters = ["a", "b", "c"];
letters[5] = "f";
console.log(letters, letters.length);
letters.length = 2;
console.log(letters);
letters.length = 4; // growing length adds holes, not elements
console.log(letters, 3 in letters);
[ 'a', 'b', 'c', <2 empty items>, 'f' ] 6
[ 'a', 'b' ]
[ 'a', 'b', <2 empty items> ] false
length must be an integer from 0 to 2³² − 1; anything else throws a RangeError.
Emptying an array
There are two ways to "empty" an array, and they're not the same:
const shared = [1, 2, 3];
const alias = shared;
alias.length = 0; // empties THE array: everyone sees it
console.log(shared);
let list = [1, 2, 3];
const kept = list;
list = []; // points list at a NEW array; the old one is untouched
console.log(kept);
[]
[ 1, 2, 3 ]
arr.length = 0 (or arr.splice(0)) clears the array in place, affecting every variable that refers to it. arr = [] creates a new array and only works with let. Choose based on whether other code should see the change.
Sparse arrays and holes
A sparse array has gaps: indexes below length with no element at all. They come from array literals with double commas, new Array(n), writing past the end, setting length larger, or delete:
const big = [];
big[1000] = "x";
console.log(big.length, Object.keys(big).length); // length 1001, one element
const values = [1, 2, 3];
delete values[1];
console.log(values, values.length, 1 in values);
1001 1
[ 1, <1 empty item>, 3 ] 3 false
A hole is not the same as an element holding undefined, even though both read as undefined:
const withHole = [, "b"];
const withUndefined = [undefined, "b"];
console.log(0 in withHole, 0 in withUndefined, withHole[0] === withUndefined[0]);
false true true
The difference shows up because array methods disagree about holes. Older methods (ES5) skip them; newer ones (ES2015 and later) treat them as undefined:
const sparse = [1, , 3];
const viaForOf = [];
for (const v of sparse) viaForOf.push(v);
const viaForEach = [];
sparse.forEach((v) => viaForEach.push(v));
console.log("for...of:", viaForOf);
console.log("forEach: ", viaForEach);
console.log("map: ", sparse.map((x) => x * 2));
console.log("filter: ", sparse.filter(() => true));
console.log("includes / indexOf:", sparse.includes(undefined), sparse.indexOf(undefined));
console.log("join / JSON:", sparse.join("-"), JSON.stringify(sparse));
for...of: [ 1, undefined, 3 ]
forEach: [ 1, 3 ]
map: [ 2, <1 empty item>, 6 ]
filter: [ 1, 3 ]
includes / indexOf: true -1
join / JSON: 1--3 [1,null,3]
Treat holes as undefined | Skip holes |
|---|---|
for...of, spread, Array.from, entries, keys, values | forEach, map (keeps the hole), filter, reduce, some, every |
find, findIndex, findLast, includes, at | indexOf, lastIndexOf, for...in, Object.keys |
toSorted, toReversed, with, fill | sort (moves holes to the end), flat (removes them) |
The practical lesson: avoid creating sparse arrays. They're confusing, and engines store very sparse arrays in a slower dictionary mode. To turn holes into real undefined values, use Array.from(sparse) or [...sparse]; to drop them, use sparse.filter(() => true).
Adding and removing elements
The next articles cover the methods in detail; here's the overview:
| Operation | End | Start | Anywhere |
|---|---|---|---|
| Add (mutating) | push(x) | unshift(x) | splice(i, 0, x) |
| Remove (mutating) | pop() | shift() | splice(i, 1) |
| Copy with a change | [...a, x] | [x, ...a] | toSpliced(i, 1), with(i, x) |
push adds one or more elements at the end and is the same as arr[arr.length] = x. pop removes and returns the last element. shift and unshift do the same at the start, moving every other element, so they're slower on very large arrays.
Don't use delete on arrays
delete arr[i] removes the element but doesn't shift the others down or change length: it leaves a hole. To remove an element and close the gap, use splice, or filter to build a new array:
const withDelete = ["a", "b", "c"];
delete withDelete[1];
console.log(withDelete, withDelete.length);
const withSplice = ["a", "b", "c"];
withSplice.splice(1, 1);
console.log(withSplice, withSplice.length);
[ 'a', <1 empty item>, 'c' ] 3
[ 'a', 'c' ] 2
Arrays of arrays
JavaScript has no built-in multidimensional arrays, but an array of arrays works the same way: index twice.
const times = Array.from({ length: 4 }, (_, row) =>
Array.from({ length: 4 }, (_, col) => row * col),
);
console.log(times[3][2], times.length, times[0].length);
console.log(times.at(-1));
6 4 4
[ 0, 3, 6, 9 ]
Each row is a separate array, so rows can even have different lengths ("jagged" arrays). Remember to create each row separately (article 54), and use structuredClone to copy the whole grid.
Common questions
Can arrays be negative-indexed like in Python?
Not with brackets: arr[-1] reads a property named "-1", which normally doesn't exist. Use arr.at(-1), and slice(-n) for the last n elements.
How do I check whether an index is valid?
Number.isInteger(i) && i >= 0 && i < arr.length. To tell a hole from a stored undefined, use i in arr or Object.hasOwn(arr, i).
Is length the number of elements?
For dense arrays, yes. For sparse arrays, it's one more than the highest index, so it can be larger than the element count: Object.keys(arr).length counts actual elements.
Can I make an array that can't change?
Object.freeze(arr) makes it read-only: push, assignment and length changes fail, with a TypeError in strict mode. Freezing is shallow, so nested arrays and objects can still change (part 14).
Summary
- Read and write with
arr[i]; missing indexes giveundefined, never an error. - Indexes are property names that are integers from 0 to 2³² − 2; other keys like
"-1"are ordinary properties. arr.at(-1)reads from the end;arr[-1]doesn't.lengthis one more than the highest index: writing past the end grows it, setting it smaller deletes elements.arr.length = 0empties the array for everyone;arr = []makes a new one.- Holes (from
[1,,3],new Array(n),deleteor writing far past the end) aren'tundefinedelements, and methods disagree about them; avoid them. - Remove elements with
spliceorfilter, notdelete.
Practice Questions
What does this print?
const a = [1, 2, 3];
a[10] = 11;
console.log(a.length, a.filter(() => true).length);
Answer
11 4. Writing index 10 sets length to 11; filter skips the seven holes, leaving four real elements.
What does this print?
const a = ["x", "y", "z"];
a.length = 1;
a.push("w");
console.log(a);
Answer
[ 'x', 'w' ]. Truncating deletes "y" and "z", and push adds at the new end.
Write a function last(arr, n) that returns the last n elements of an array, without mutating it.
Answer
const last = (arr, n) => (n === 0 ? [] : arr.slice(-n));
slice with a negative start counts from the end; n === 0 needs a special case because slice(-0) returns the whole array.
Why is delete list[0] a poor way to remove the first element, and what should you use?
Answer
It leaves a hole at index 0 and doesn't change length or shift the other elements. Use list.shift() to remove it in place, or list.slice(1) for a new array without it.
Previous: JavaScript Arrays: Creating Arrays with Literals, Spread, Array.of and Array.from
Next: JavaScript Array Iteration: forEach, map and filter Explained

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.