The length
property sets or returns the number of elements in an array.
How do you find the length of an array in JavaScript?
The JavaScript array length property states the number of items in an array.
To find the length of an array, reference the object array_name. length.
The length property returns an integer.
In this tutorial, you’ll learn about the JavaScript Array length
property and how to handle it correctly.
Syntax
Return the length of an array:
array.length
Set the length of an array:
array.length = number
Return Value
The number of elements in the array. It returns the integer just greater than the highest index in an Array
.
Below are the examples of the Array length property.
Example – Get Length
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;
let city = ["California", "Barcelona", "Paris", "Kathmandu"];
// find the length of the city array
let len = city.length;
console.log(len);
// Output: 4
var companyList = ["Apple", "Google", "Facebook", "Amazon"];
console.log(companyList.length); // Output: 4
var randomList = ["JavaScript", 44];
console.log(randomList.length); // Output: 2
var emptyArray = [];
console.log(emptyArray.length); // Output: 0
Example – Set Length
You can also reassign the length
property of an Array
using the assignment operator =
.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length = 2;
This can be used to truncate or extend a given array.
Using Array length in for loop
var languages = ["JavaScript", "Python", "C++", "Java", "Lua"];
// languages.length can be used to find out
// the number of times to loop over an array
for (i = 0; i < languages.length; i++){
console.log(languages[i]);
}
Changing length property of Array
var languages = ["JavaScript", "Python", "C++", "Java", "Lua"];
// truncate the Array to 3 elements
languages.length = 3
// Output: [ 'JavaScript', 'Python', 'C++' ]
console.log(languages)
// extend the Array to length 6
languages.length = 6
// Output: [ 'JavaScript', 'Python', 'C++', <3 empty items> ]
console.log(languages)
If the assigned value is more than the original Array
length, empty items are appended to the end of the Array.