JavaScript Code


How to iterate over array elements using for…in in JavaScript?


Iterate over array elements using for…in in JavaScript

In this tutorial, you are given an array. Write a JavaScript program to iterate over the elements of the array using for…in loop.

Solution

In JavaScript, for…in loop is used to iterate over the keys of an object. For an array indices are the keys. Therefore, we can use for…in loop to iterate over the indices of an array, and thus access the elements using index.

Program

In the following program, we take an array of strings in fruits. And use a for…in loop statement to iterate over the elements of this array.

let fruits = ['apple', 'banana', 'cherry' ]

for ( let index in fruits ) {
    console.log(fruits[index]);
}


copyright @2022