JavaScriptArrays
Array. prototype. length
The number of elements in the array, which you can also change.
- Returns
- An integer: the number of elements.
- Changes the original
- No
Example
#JavaScript
const lessons = ['HTML', 'CSS', 'JS']
console.log(lessons.length)
lessons.length = 2
console.log(lessons)
console.log(lessons[lessons.length - 1])Console
3
['HTML', 'CSS']
CSS
Definition and usage
#The length property returns the number of elements in the array, or more precisely, the index of the last element plus one. An empty array has a length of 0.
You can also set the length. Shrinking length trims the array, removing elements from the end, and setting length = 0 clears the array in place, which every other part of the code sharing that array will notice.
Increasing length adds holes, which behave differently from undefined in some methods. It’s usually best to avoid that.
Syntax
#Syntax
array.length
array.length = numberBrowser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- For the last element,
at(-1)is more convenient thanarray[array.length - 1]. - Checking for an empty array:
if (items.length === 0). The array itself, even when empty, is a truthy value.
Related entries
#Spotted a mistake or missing an example? Write to us.