Skip to main content

Changing length manually

The length property of a JavaScript array is special. It does not just show the length, it also controls the number of elements. If you change it manually, it directly affects the array's contents.

Example 1: Decreasing length

javascript
const arr = [1, 2, 3, 4, 5]; arr.length = 3; console.log(arr); // [1, 2, 3]

If you decrease length, all elements with larger indexes are removed.

Example 2: Increasing length

javascript
const arr = [1, 2, 3]; arr.length = 6; console.log(arr); // [1, 2, 3, <3 empty items>] console.log(arr[4]); // undefined

If you increase length, "empty slots" (empty items) are added. They are not equal to undefined - they are empty cells that "don't exist" in a sense, so, for example, forEach() skips them.

Example 3: Clearing an array with length = 0

javascript
const arr = [10, 20, 30]; arr.length = 0; console.log(arr); // []

A very convenient way to clear an array - without recreating it.

Important to know:

ActionWhat happens
arr.length = smallertruncates the array
arr.length = largeradds empty cells
arr.length = 0clears the array
arr.length read onlyshows the number of elements

In short:

The length property does not just tell you "how many elements", it controls the array's size. Decrease it and you remove elements, increase it and you create empty slots.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.