Arrays: creating, length and holes

An array is an ordered list of values under one name, and every value has a position: the first sits at index 0 and the last at length - 1. The length belongs to the array itself and is not a count that something else keeps, which is why writing to an index past the end changes it. Like an object, an array is a JavaScript reference, so two names can hold the same list.

This lesson covers the ways an array is created, what the index and the length do at the edges, the holes that delete leaves behind, and the two static methods that build an array out of something else: Array.from and Array.of.

Creating an array

A literal is the usual way, and the brackets say where the items are. The constructor is the interesting case: new Array(3) reads its single number argument as a length and makes three empty slots, while new Array(1, 2, 3) reads three arguments as three items. The call Array.of was added to the language to take arguments as items in every case.

const letters = ['a', 'b', 'c']; const threeSlots = new Array(3); const oneNumber = Array.of(3); const threeNumbers = new Array(1, 2, 3); console.log('a literal:', letters.length, JSON.stringify(letters)); console.log('new Array(3):', threeSlots.length, JSON.stringify(threeSlots)); console.log('Array.of(3):', oneNumber.length, JSON.stringify(oneNumber)); console.log('new Array(1, 2, 3):', threeNumbers.length, JSON.stringify(threeNumbers)); console.log('the two calls agree:', JSON.stringify(Array.of(1, 2, 3)) === JSON.stringify(new Array(1, 2, 3)));

node creating.js

a literal: 3 ["a","b","c"]
new Array(3): 3 [null,null,null]
Array.of(3): 1 [3]
new Array(1, 2, 3): 3 [1,2,3]
the two calls agree: true

Four ways to make an array and two lengths that look the same for different reasons: the literal and new Array(3) both have three positions, but only the literal has values in them. The last line is the point of Array.of: with more than one argument the two calls agree, and the single number is the only case where they do not. A number from a variable is therefore a reason to reach for Array.of, which always means one item.

Length and indexing

Reading a position works with brackets, and at takes a negative number that counts from the end. Reading a position that was never written gives undefined and no error. The length is writable: a smaller number drops the items past it, and a larger one leaves holes at the end.

const items = ['a', 'b', 'c']; console.log('index 0:', items[0]); console.log('the last one:', items[items.length - 1]); console.log('at(-1):', items.at(-1)); console.log('past the end:', items[3]); console.log('length counts the gaps too:', items.length); items[5] = 'f'; console.log('after a write to index 5:', items.length); console.log('the gap:', JSON.stringify(items)); items.length = 2; console.log('after length = 2:', items.length, JSON.stringify(items));

node length.js

index 0: a
the last one: c
at(-1): c
past the end: undefined
length counts the gaps too: 3
after a write to index 5: 6
the gap: ["a","b","c",null,null,"f"]
after length = 2: 2 ["a","b"]

The write to index 5 put one value at the end and left two positions empty, and the length became 6 because the last index plus one is what the property reports. The two null values in the JSON line are how that serialisation writes a position with nothing in it, not values of the array. The last line is the other direction: a shorter length cut the array down, which is a cheap way to empty a list and an easy way to lose items by accident.

Holes

A hole is a position that has no value at all, which is not the same as a position holding undefined. delete leaves one, and the in operator tells a hole from a value. The array methods disagree about what to do with it: map and forEach skip a hole and keep it, while Array.from reads it as undefined and calls the callback.

const holes = [1, 2, 3]; delete holes[1]; console.log('length:', holes.length); console.log('as JSON:', JSON.stringify(holes)); console.log('is there an index 1?', 1 in holes); console.log('and an index 0?', 0 in holes); const mapped = holes.map((value) => value * 2); console.log('map keeps the hole:', mapped.length, JSON.stringify(mapped)); const filled = Array.from(holes, (value) => (value === undefined ? 'empty' : value * 2)); console.log('Array.from does not:', JSON.stringify(filled)); let visits = 0; holes.forEach(() => { visits += 1; }); console.log('forEach visits:', visits); console.log('own keys:', Object.keys(holes).join(','));

node holes.js

length: 3
as JSON: [1,null,3]
is there an index 1? false
and an index 0? true
map keeps the hole: 3 [2,null,6]
Array.from does not: [2,"empty",6]
forEach visits: 2
own keys: 0,2

The length stayed at three and index 1 stopped existing, which in reports and Object.keys confirms with two keys. map returned an array of the same length with the same hole, and the callback ran twice, not three times. The Array.from call worked from a length and visited every position, which is why it is the method to use when a gap has to become a value.

Array.from and Array.of

Array.from takes anything iterable, which is a string, a Set, a Map, or the arguments object of a function, and builds an array from what it yields. Its second argument is a function called for each value with the index, so a range of numbers is one call. Array.of does the small job that new Array gets wrong: it keeps every argument as an item.

console.log('from a string:', JSON.stringify(Array.from('abc'))); console.log('from a Set:', JSON.stringify(Array.from(new Set([1, 2, 2, 3])))); console.log('from a Map:', JSON.stringify(Array.from(new Map([['a', 1]])))); console.log('from a length:', JSON.stringify(Array.from({ length: 4 }, (value, index) => index * index))); function toArray() { return Array.from(arguments); } console.log('from arguments:', JSON.stringify(toArray('x', 'y'))); const mixed = Array.of('a', 1, null); console.log('Array.of keeps every argument:', JSON.stringify(mixed));

node from.js

from a string: ["a","b","c"]
from a Set: [1,2,3]
from a Map: [["a",1]]
from a length: [0,1,4,9]
from arguments: ["x","y"]
Array.of keeps every argument: ["a",1,null]

Each line is a different source and the same result type. The string was split into code points, the Set gave its unique values, the Map gave a pair per entry, and the object with a length gave four numbers because the second argument is called with the index. The arguments object is worth knowing about in old code, since it is array-like but not an array and has no map of its own.

Exercises

  1. Print new Array(2) and Array.of(2) from creating.js. Which one has two items, and what does each length say?
  2. In length.js, write to index 3 instead of 5. How long is the array then, and how many holes does the JSON line show?
  3. Delete two positions in holes.js and print the number of calls map makes. Which positions does it visit?
  4. Build an array of the even numbers from 0 to 10 with one Array.from call. What does the callback look like?
  5. Pass a number and a string to Array.of and to new Array. Which of the two calls throws a RangeError, and why?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is the length of new Array(3)?

    Answer

    3, with three empty positions

    A single number argument is read as a length, which is the trap that Array.of was added for.

  2. Which call makes an array with one item, the number 3?

    Answer

    Array.of(3)

    Array.of takes every argument as an item, so one number gives one item.

  3. What does this program print? const a = ["x", "y"]; a[4] = "z"; console.log(a.length, 2 in a);

    Answer

    5 false

    The write to index 4 makes the length 5 and leaves indexes 2 and 3 as holes.

  4. What does this program print? const a = [1, 2, 3]; a.length = 1; console.log(a.length, a[1]);

    Answer

    1 undefined

    A shorter length drops the items past it, so only the first one is left.

  5. What is the difference between a hole and a position holding undefined?

    Answer

    A hole has no index at all, so 1 in a is false, while a stored undefined has one

    The in operator and Object.keys see the difference, and map and forEach skip a hole but visit a stored undefined.

  6. What does this program print? const a = [1, 2, 3]; delete a[1]; let n = 0; a.forEach(() => { n += 1; }); console.log(a.length, n, 1 in a);

    Answer

    3 2 false

    The length stays, forEach skips the hole and visits two positions, and the index is gone.

  7. What does this program print? console.log(Array.from("ab").length, Array.of("ab").length);

    Answer

    2 1

    Array.from walks the string and gives one item per character, and Array.of keeps the string as one item.

  8. What does this program print? console.log(JSON.stringify(Array.from({ length: 3 }, (v, i) => i)));

    Answer

    [0,1,2]

    The object with a length gives three positions, and the second argument of Array.from receives the index of each.

  9. Which method is the safe way to read the last item of an array?

    Answer

    at(-1), which counts from the end and gives undefined on an empty array

    A negative number in brackets is a property name, not a position, so at is the method that counts from the end.

  10. Why does Array.from split a string into characters while a spread also works?

    Answer

    Both use the iteration protocol of the string, which yields one character at a time

    A string is iterable, so every consumer of the protocol reads the same code points.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev