.length

Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
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: 5
colors.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.

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn JavaScript on Codecademy