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
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
const arr = [1, 2, 3];
arr.length = 6;
console.log(arr); // [1, 2, 3, <3 empty items>]
console.log(arr[4]); // undefinedIf 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
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:
| Action | What happens |
|---|---|
arr.length = smaller | truncates the array |
arr.length = larger | adds empty cells |
arr.length = 0 | clears the array |
arr.length read only | shows the number of elements |
In short:
The
lengthproperty 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 readyA concise answer to help you respond confidently on this topic during an interview.