Home / Questions / An example of using the for...of loop to iterate over the elements of an array:
Explanatory Question

An example of using the for...of loop to iterate over the elements of an array:

👁 126 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

In JavaScript, you can use the for...in loop to iterate over the properties of an object, but it's not recommended for iterating over arrays. Instead, you should use the for...of loop or array methods like forEach, map, filter, etc.

Here's an example of using the for...of loop to iterate over the elements of an array:


let myArray = [1, 2, 3, 4, 5];

for (let element of myArray) {
    console.log(element);
}

Alternatively, you can use array methods like forEach for a more concise and expressive way:


let myArray = [1, 2, 3, 4, 5];

myArray.forEach(function(element) {
    console.log(element);
});

Using for...in loop for arrays is not recommended because it iterates over all enumerable properties, including those inherited from the object's prototype chain. This can lead to unexpected behavior if the array has additional properties or if someone has modified the Array prototype. Therefore, it's safer and more appropriate to use for...of or array methods for iterating over arrays.


If you want to iterate over the characters of a string, you can use the for...of loop as well. Here's an example with the string "Rumman Ansari":


let myString = "Rumman Ansari";

for (let char of myString) {
    console.log(char);
}

This will output each character of the string on a separate line:


R
u
m
m
a
n

A
n
s
a
r
i

The for...of loop is versatile and can be used to iterate over the elements of arrays, strings, and other iterable objects in JavaScript.