Arrays — ordered, growable, and objects underneath¶
Level: 101 · for anyone who has written a line of JavaScript
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: An array is an object whose index keys are strings and whose length follows the largest index: on an empty array a[5] = "x" makes length 6, a[-1] = "y" adds a property that length ignores, and a.length = 0 deletes the indexed elements only.
Keywords: Array, Array.isArray, Array.from, Array.of, length, at
What the finished page will answer¶
- What happens to
lengthwhen you assigna[5]on an empty array, and what are the keys of the result? - Why does
a[-1] = "y"leavelengthalone, and why doesa.at(-1)still return the last element? - What does
a.length = 0delete, and what does it leave behind? - Why is
typeof []"object", and what doArray.isArrayandinstanceof Arraysay about an array, an array-like object and a typed array? - Why does
new Array(3)make three empty slots whileArray.of(3)makes[3], and what doesArray.from({ length: 3 }, (_, i) => i)make?
Examples it will need¶
-
array_basics_length_js.js— an empty array aftera[5] = "x",a[-1] = "y"anda.length = 0: itslength, its keys and whata[5],a[-1]anda.at(-1)return, one line per step -
array_basics_is_array_js.js—typeof,Array.isArrayandinstanceof Arrayfor an array, an array-like object and a typed array, thennew Array(3),Array.of(3)andArray.from({ length: 3 }, (_, i) => i)side by side
See also¶
- Holes — what the unassigned slots below index 5 really are
- Property keys — why index keys are strings, and the order keys come back in
typeof— whytypeofcannot tell an array from an object- Mutating and copying methods — which array methods change the array in place
- Arrays and tuples — the types TypeScript gives arrays and fixed-length tuples
- Rust: Array or
Vec? ↗ — in Rust, fixed arrays and growableVecare separate types; JavaScript has one