JavaScript Code

How to iterate over array elements using for…in?


Problem Statement

given an array, write a JavaScript program to iterate over the elements of the array using for…in loop

Solution

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

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

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


copyright @2022