JavaScript Array length
Syntax & Examples
Array.length property
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.
Syntax of Array.length
The syntax of Array.length property is:
length
This length property of Array reflects the number of elements in an array.
Return Type
Array.length returns value of type Number
.
✐ Examples
1 Getting the length of an array
In JavaScript, we can use the length property to get the number of elements in an array.
For example,
- We define an array variable arr with elements [1, 2, 3, 4, 5].
- We access the length property of the array to get its length.
- The length of the array, which is 5, is stored in the variable arrLength.
- We log arrLength to the console using console.log() method.
JavaScript Program
const arr = [1, 2, 3, 4, 5];
const arrLength = arr.length;
console.log(arrLength);
Output
5
2 Checking if an array is empty
We can use the length property to check if an array is empty by comparing its length to 0.
For example,
- We define an empty array variable emptyArr.
- We check if the length of emptyArr is equal to 0.
- If the length is 0, we log 'Array is empty' to the console; otherwise, we log 'Array is not empty'.
JavaScript Program
const emptyArr = [];
if (emptyArr.length === 0) {
console.log('Array is empty');
} else {
console.log('Array is not empty');
}
Output
Array is empty
3 Iterating through elements of an array using length property
We can use the length property in a loop to iterate through elements of an array.
For example,
- We define an array variable fruits with elements ['apple', 'banana', 'cherry'].
- We use a for loop to iterate through each element of the array using the length property.
- Inside the loop, we log each element to the console.
JavaScript Program
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Output
apple banana cherry
Summary
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.