In JavaScript, the .length property is used to track the number of elements in an array. However, unlike many other languages, the length property in JavaScript is dynamic and writable, meaning it can be used to both read and manipulate the size of an array.
1. Basic Usage
By default, the .length property returns the total number of items currently in the array. It is always one higher than the highest index in the array.
const tools = ['Hammer', 'Screwdriver', 'Wrench'];
console.log(tools.length); // 3
2. Setting the Length (Truncating)
Because the length property is writable, you can manually change it. If you set it to a value smaller than the current size, JavaScript will permanently delete the extra elements.
const colors = ['red', 'blue', 'green', 'yellow'];
colors.length = 2;
console.log(colors); // ["red", "blue"]
console.log(colors[2]); // undefined (it's gone!)
3. Extending an Array
If you set the length to a value larger than the current size, the array becomes “sparse.” JavaScript creates empty slots (holes) in the array.
const fruits = ['apple'];
fruits.length = 3;
console.log(fruits); // ["apple", empty × 2]
console.log(fruits[1]); // undefined
4. Length vs. Highest Index
The length property is not necessarily a count of how many items are actually inside if the array is sparse; it is simply the highest index + 1.
const sparseArray = [];
sparseArray[99] = "last item";
console.log(sparseArray.length); // 100
5. Common Patterns using .length
A. Clearing an Array
The fastest way to completely empty an array is to set its length to zero.
let myData = [1, 2, 3, 4, 5];
myData.length = 0;
console.log(myData); // []
B. Iterating through an Array
The most common use for .length is in for loops to ensure you visit every element.
const names = ['Alice', 'Bob', 'Charlie'];
for (let i = 0; i < names.length; i++) {
console.log(names[i]);
}
C. Accessing the Last Element (Old Way)
Before the .at() method was introduced, .length was the standard way to grab the final item.
const arr = [10, 20, 30];
const lastItem = arr[arr.length - 1]; // 30
