JavaScript - Length of an Array in JS
Last Updated :
12 Nov, 2024
Improve
These are the following approaches to find the length of the given array:
1. Using length Property - Mostly Used
In this approach, we have used the length property to determine the length of an array.
let a = [12, 4.7, 9, 10]
console.log(a.length)
Output
4
2. Using for of and for in Loop
We have used for of and for in loops to traverse each element of the array and increment a counter variable. we have defined an array '
a' and initializes a variable size
to 0. It then iterates over the elements of the array using both for-in and for-of
loops, incrementing size
for each element. Finally, it prints the lengths obtained from both loops.
let a = [12, 4.7, 9, 10]
let s = 0;
for (let element in a) {
s++;
}
console.log(s)
s = 0;
for (let element of a) {
s++;
}
console.log(s)
Output
4 4
3. Using reduce() Method
The reduce() method can be used to count the number of elements in the array by incrementing a counter for each element.
let a = [12, 4.7, 9, 10];
console.log(a.reduce((size) => size + 1, 0));
Output
4