Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

`length`: the writable property of an array

Read `arr.length` to get an array’s length, or assign to it to truncate the same array or extend it without creating elements.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

arr.length
arr.length = newLength

The term Array.length mutable property refers to arr.length, an own data property of an Array instance, not the Array constructor’s length. It starts out writable and is neither enumerable nor configurable. It is greater than every own array index and can exceed the number of elements actually present.

Reducing length deletes own elements at or above the new length. Setting arr.length = 0 clears an ordinary array in place: every reference to that array sees the change. Increasing the length leaves holes, not elements with the value undefined, and does not restore deleted elements. Creating an element at a valid array index i at or beyond the current length raises the length to i + 1.

The length is a Number integer from 0 through 2 ** 32 - 1. A write to a writable length coerces the assigned value: for example, "3" is accepted as 3, but 2.5, -1, and 2 ** 32 throw RangeError. Converting a Symbol or BigInt throws TypeError instead.

If truncation hits a non-configurable element, it stops at that index. The length becomes that index plus one, and any higher elements already deleted stay deleted. You can also make length permanently non-writable with writable: false. This blocks assignments to length and additions that would extend the array, but does not prevent all element changes. In either case, a failed assignment throws TypeError in strict mode; outside strict mode it does not throw.

Examples

(() => {
  "use strict";
  const arr = ["a", "b", "c"];
  const alias = arr;

  arr.length = 1;
  console.log(`${alias.length}: ${alias.join(",")}`);

  arr.length = 3;
  arr[2] = undefined;
  console.log(`${arr.length}: ${Object.hasOwn(arr, 1)}, ${Object.hasOwn(arr, 2)}`);

  arr[4] = "e";
  console.log(`${arr.length}: ${arr[4]}`);

  try {
    arr.length = 2.5;
  } catch (error) {
    console.log(`${error.name}: ${arr.length}`);
  }
})();

Result

1: a
3: false, true
5: e
RangeError: 5

`alias` sees the same array get shorter. After extension, `Object.hasOwn` distinguishes the hole at index `1` from the explicit `undefined` at index `2`. Writing at index `4` raises the length to `5`; the rejected `2.5` leaves it there.

Related lessons

  • JavaScript · Lesson 20 · Advanced · Version: 4

Sources