.length
Anonymous contributor
Anonymous contributor5 total contributions
Anonymous contributor
Published Jun 22, 2021Updated Jun 8, 2023
Contribute to Docs
The .length
array property returns the specific number of elements in the array.
Syntax
array.length;
Setting the length with a positive value that is lower than the actual array length will delete items at end.
Examples
const daysOfWeek = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday',];const lengthOfWeek = daysOfWeek.length;console.log(lengthOfWeek);// Output: 7
Iterating over an array using length:
const numbers = [10, 20, 30, 40, 50];const length = numbers.length;for (let i = 0; i < length; i++) {numbers[i] *= 2;}console.log(numbers);// Output: [20, 40, 60, 80, 100]
Shortening an array:
const colors = ['purple', 'orange', 'yellow', 'green', 'blue'];console.log(colors.length);// Output: 5colors.length = 3;console.log(colors);// Output: ['purple', 'orange', 'yellow']
Codebyte Example
The example below defines a new array groceries
and then logs the four array items to the console. Next, to delete the last item in the array, its length
property is set to 3. Finally, to confirm the last item has been removed, the updated array and the value of item 4 (undefined
) are logged to the console.
All contributors
- Anonymous contributorAnonymous contributor5 total contributions
- christian.dinh2476 total contributions
- Anonymous contributorAnonymous contributor3071 total contributions
- robgmerrill124 total contributions
- Anonymous contributor
- christian.dinh
- Anonymous contributor
- robgmerrill
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.