JavaScript(JS) array method - length
The length
property is not an array method, but a property of JavaScript arrays. It returns or sets the number of elements in an array.
Here's an example of how to use the length
property:
let array = ['apple', 'banana', 'orange']; console.log(array.length); // 3 array.length = 5; console.log(array); // ['apple', 'banana', 'orange', undefined, undefined] array.length = 2; console.log(array); // ['apple', 'banana']
In this example, we have an array array
containing the elements ['apple', 'banana', 'orange']
. We use the length
property to get the number of elements in the array, which is 3. We then set the length
property to 5, which adds two undefined
elements to the end of the array. Finally, we set the length
property to 2, which removes the last element from the array.
Note that changing the length
property of an array can have unintended consequences, such as adding or removing elements from the array. To add or remove elements from an array, it's generally better to use array methods such as push()
, pop()
, shift()
, and unshift()
.