How to use for of and for in loop In Javascript
Here, we will use the for of and for in loop and traverse each element of array and will increase size variable on each iteration by one.
// Defining the array
let arr = [12, 4.7, 9, 10]
// Defining the length variable
let size = 0;
// Looping using for-in loop
for (let element in arr) {
size++;
}
// Printing the length
console.log(`Length by using for in loop ->; ${size}`)
// Reseting the value of variable
size = 0;
// Looping using for-or loop
for (let element of arr) {
size++;
}
// Printing the length
console.log(`Length by using for of loop ->; ${size}`)
Output
Length by using for in loop ->; 4 Length by using for of loop ->; 4
Explanation:
The above code defines an array arr
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.
JavaScript Program to Determine the Length of an Array
Finding the length of an array in JavaScript refers to the process of determining the number of elements contained within an array.
Below are the approaches used to Determine the length of an array in JavaScript:
Here, we will use the length property of the array to determine the length of the array. It will return the number of elements in an array.