The length property of the Array class in JavaScript reflects the number of elements in an array. It returns an integer representing the length of the array.
The syntax of Array.length property is:
length
This length property of Array reflects the number of elements in an array.
Array.length returns value of type Number
.
In JavaScript, we can use the length property to get the number of elements in an array.
For example,
const arr = [1, 2, 3, 4, 5];
const arrLength = arr.length;
console.log(arrLength);
5
We can use the length property to check if an array is empty by comparing its length to 0.
For example,
const emptyArr = [];
if (emptyArr.length === 0) {
console.log('Array is empty');
} else {
console.log('Array is not empty');
}
Array is empty
We can use the length property in a loop to iterate through elements of an array.
For example,
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
apple banana cherry
In this JavaScript tutorial, we learned about length property of Array: the syntax and few working examples with output and detailed explanation for each example.