Array length and missing positions
Quick answer
Array length describes the index range, not necessarily the number of present elements. Increasing length creates missing positions rather than assigning undefined values.
How it works
For a dense array the last index is length - 1 if length is positive. Assigning a valid array index at or above length extends it. Reducing length removes own indexed properties beyond the new length on ordinary writable arrays.
const a = [3, 6, 9];console.log(a.length, a[a.length - 1]);Expected output in Node.js:
3 9The last position is index two.
const a = [4];a.length = 3;console.log(a.length, a[2], 2 in a);a.length = 1;console.log(a.length);Expected output in Node.js:
3 undefined false1The enlarged range has holes. The in operator checks property existence, not the read value.
Common mistakes
An empty array has no last element. Do not confuse a hole with an explicitly stored undefined. The valid length range is 0 through 2^32−1.
Practice
Compare a dense array and one whose length was increased; inspect their lengths.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Array length and missing positions — Knowledge Check
Apply the taught concept and reason about the result.
What is the length of [2,5,8]?
After const a=[1]; a.length=4; what is 3 in a?
After const a=[1,2,3]; a.length=1; what is a[2] in an ordinary unmodified environment?
What does const a=[]; a[4]=9; produce for a.length?
Is an array's length necessarily the count of existing elements?