JavaScript array length and what happens when you change it

items.length is the length of the index range of a JavaScript array. It equals the element count in an array without holes, but includes empty slots. Reducing the length deletes elements outside the new range. Increasing it again does not restore them.

Length and the last position

Indexes start at zero. With length 4, the last position is 3. Compare the colors.length property with colors.at(-1) below. In an ordinary array, at(-1) gives undefined if the last slot is empty or the array is empty. colors[-1] reads a property named "-1". See ECMAScript: at().

const colors = ['red', 'green', 'blue', 'black'];
console.log(colors.length); // 4
console.log(colors[colors.length - 1]); // 'black'
console.log([].length); // 0
console.log(colors.at(-1)); // 'black'
console.log([].at(-1));    // undefined

Distinguish a hole from stored undefined

Assigning the first value of an empty array at index 10 raises its length to 11, with only one actual element. Increasing the length does not give all the positions values.

const items = [];
items[10] = 'X';
console.log(items.length);         // 11
console.log(Object.keys(items));   // ['10']
console.log(items[0]);             // undefined
console.log(Object.hasOwn(items, 0)); // false

items[0] = undefined;
console.log(items[0]);             // undefined
console.log(Object.hasOwn(items, 0)); // true
console.log(items.length);         // 11

Reading a hole and an element set to undefined gives the same value, but the structure differs. Below, Object.hasOwn(items, 0) is false before assignment and true afterward. Object.keys() lists enumerable own properties, including named string properties you add.

Change length or make a shorter copy

The example cuts an array of length 4 to 2 and extends it back to 4. C and D are deleted. Another reference created by const alias = letters sees the same deletions. Use letters.slice(0, 2) to copy the first two positions into a new array.

const letters = ['A', 'B', 'C', 'D'];
const alias = letters;
letters.length = 2;
console.log(alias);   // ['A', 'B']
letters.length = 4;
console.log(letters.length); // 4
console.log(Object.hasOwn(letters, 2)); // false

For a normally writable array, length is an integer from 0 to 2 ** 32 - 1. Assigning -1 or 2.5 throws a RangeError. A nonwritable length or a nonconfigurable index can prevent truncation. See ECMAScript: Array length and ECMAScript: ArraySetLength for the precise rules.

Complete example: compare length and existing indexes

Save the HTML as array-length.html in UTF-8 and open it. Click Set index 10 to X to get length 11, then Set length to 3 and Set length to 7. The value at 10 is removed. Only 0, 1, 2 remain in the index list.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Explore array length and holes</title>
</head>
<body>
<button id="add" type="button">Set index 10 to X</button>
<button id="shorten" type="button">Set length to 3</button>
<button id="extend" type="button">Set length to 7</button>
<button id="define" type="button">Set index 4 to undefined</button>
<button id="reset" type="button">Reset</button>
<pre id="output" aria-live="polite"></pre>
<script>
let items = ['A', 'B', 'C'];
const output = document.querySelector('#output');

function show() {
  const keys = Object.keys(items);
  let indexFour = "outside the range";
  if (items.length > 4) {
    indexFour = Object.hasOwn(items, 4) ? String(items[4]) : "hole";
  }
  output.textContent = `length: ${items.length}\n` +
    `Existing indexes: ${keys.length ? keys.join(', ') : "(none)"}\n` +
    `Existing entries: ${keys.map(key => `${key}:${items[key]}`).join(', ') || "(none)"}` +
    `\nitems[4]: ${indexFour}`;
}

document.querySelector('#add').addEventListener('click', () => {
  items[10] = 'X';
  show();
});
document.querySelector('#shorten').addEventListener('click', () => {
  items.length = 3;
  show();
});
document.querySelector('#extend').addEventListener('click', () => {
  items.length = 7;
  show();
});
document.querySelector('#define').addEventListener('click', () => {
  items[4] = undefined;
  show();
});
document.querySelector('#reset').addEventListener('click', () => {
  items = ['A', 'B', 'C'];
  show();
});
show();
</script>
</body>
</html>

Index 4 is now a hole. Click Set index 4 to undefined. The length stays 7, index 4 appears in the list, and its status becomes undefined. Reset creates a new array with the original three values.