Problem Statement
What does array.length return?
Explanation
The length property returns the number of elements in an array.
It is always one more than the highest index because arrays are zero-indexed.
You can also set the length property to truncate or extend an array.
Setting length to 0 is a quick way to empty an array.
The length property is automatically updated when you add or remove elements.
Code Solution
SolutionRead Only
const numbers = [10, 20, 30, 40, 50];
// Get length
console.log(numbers.length); // 5
// Access last element using length
console.log(numbers[numbers.length - 1]); // 50
// Set length to truncate
numbers.length = 3;
console.log(numbers); // [10, 20, 30]
// Set length to 0 (empty array)
numbers.length = 0;
console.log(numbers); // []
// Empty array check
const arr = [];
if (arr.length === 0) {
console.log('Array is empty');
}
// Length is always 1 more than highest index
const sparse = [1, 2, 3];
sparse[10] = 100;
console.log(sparse.length); // 11 (not 4!)