JavaScript length
In JavaScript, the length
property of an array is a built-in property that indicates the number of elements in the array. It is a dynamic property, meaning that it automatically updates as you add or remove elements from the array.
Key Points About the length
Property:
Returns the Number of Elements:
- The
length
property returns the total number of elements in an array. - The count starts from 1, so if an array has 5 elements, the
length
property will return 5.
Example:
let fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits.length); // Output: 3
- The
Dynamic Nature:
- The
length
property automatically updates as you add or remove elements from the array. - If you push a new element to the array, the
length
property increases; if you remove an element, it decreases.
Example:
fruits.push("Orange"); console.log(fruits.length); // Output: 4 fruits.pop(); console.log(fruits.length); // Output: 3
- The
Setting the
length
Property:- You can also set the
length
property manually. If you set it to a number smaller than the current number of elements, the array will be truncated (elements after the new length are removed). - If you set it to a number greater than the current number of elements, empty slots (
undefined
) will be added.
Example:
let numbers = [1, 2, 3, 4, 5]; numbers.length = 3; console.log(numbers); // Output: [1, 2, 3] numbers.length = 6; console.log(numbers); // Output: [1, 2, 3, undefined, undefined, undefined]
- You can also set the
Length with Sparse Arrays:
- If an array has "holes" (i.e., elements are not consecutive, or some indices are missing), the
length
property still reflects the highest index plus one, not just the count of elements.
Example:
let sparseArray = []; sparseArray[100] = "Element"; console.log(sparseArray.length); // Output: 101
- If an array has "holes" (i.e., elements are not consecutive, or some indices are missing), the
Non-Numeric Properties:
- The
length
property only counts numeric indices. Non-numeric properties (e.g.,array["key"] = value
) do not affect thelength
.
Example:
let arr = []; arr[0] = "A"; arr["name"] = "Array"; console.log(arr.length); // Output: 1 console.log(arr["name"]); // Output: Array
- The