Skip to content

Try our new Crash Courses!

Become a member using the button below to hide this banner and gain access to our new Crash Courses.

for…of loop – JavaScript

Length: 10 minutes

Summary

const myArray = ['hello', 'world', '!'];

for (const item of myArray) {
  console.log(item);
}

Details

The for…of loop can be used to iterate over the items in an array.

To write a for…of loop, you need an array to use. In this example we created an array called myArray. Then, write the for keyword followed by a pair of parentheses and curly braces:

const myArray = ['hello', 'world', '!'];
for () {

}

Then, declare a constant or variable inside the parentheses. You can name it whatever you want. In this example, we’re calling it item.

const myArray = ['hello', 'world', '!'];
for (const item) {

}

Then, add the of keyword and the name of an array.

const myArray = ['hello', 'world', '!'];
for (const item of myArray) {

}

Then, use the variable name you created before inside the for…of loop to access the current element in the arrray.

const myArray = ['hello', 'world', '!'];
for (const item of myArray) {
  console.log(item);
}

This example would print out the following in the browser console:

hello
world
!

Demo

Exercises

Try the following statements in the console:

const myArray = ['hello', 'world', '!'];

for (const item of myArray) {
  console.log(item);
}

You should see each item in the array print out.

Back to: JavaScript Reference > JS Loops