JavaScript .length
Published Jun 22, 2021Updated Jun 8, 2023
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.
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours