How to Get the Length of an Array in JavaScript

Contents
In this article, you will learn how to get the length of an array in JavaScript.
Getting the length of an array in JavaScript
In JavaScript, an array is a collection of values, which can be of any data type. One of the most common tasks when working with arrays is to determine their length.
Using the length property
The most common way to get the length of an array in JavaScript is by using the length property. This property returns the number of elements in the array.
Example
const fruits = ['apple', 'banana', 'orange'];
const length = fruits.length;
console.log(length); // output: 3
Using the Array.isArray() method
Before getting the length of an array, it’s important to ensure that it is actually an array. We can use the Array.isArray() method to check if an object is an array.
Example
const fruits = ['apple', 'banana', 'orange'];
if (Array.isArray(fruits)) {
const length = fruits.length;
console.log(length); // output: 3
}
Using the spread operator
We can also use the spread operator (…) to get the length of an array. The spread operator allows us to spread the values of an array into a new array. By spreading an array into a function, we can get its length.
Example
const fruits = ['apple', 'banana', 'orange'];
const length = [...fruits].length;
console.log(length); // output: 3
Using the forEach() method
The forEach() method allows us to loop through each element of an array. We can use this method to get the length of an array by incrementing a counter for each element in the array.
Example
const fruits = ['apple', 'banana', 'orange'];
let length = 0;
fruits.forEach(() => {
length++;
});
console.log(length); // output: 3