1. javascript
  2. /references
  3. /for-of-loop

The for...of Loop in JavaScript

As a traditional iteration method, the for...of loop was introduced in ES6. Since then, it has become a convenient approach to loop through iterable objects such as strings, arrays, and numerous other use cases.

The for...of Loop Syntax

let iterable = [1, 2, 3];
for (let value of iterable) {
// Output:
// 1
// 2
// 3

Let's observe the syntax elements.

The variable iterable is an array, and value is another variable that takes on the value of each element in the array as the loop iterates. The of keyword specifies the object that is being iterated over.

For...of Loop Examples

Looping Through an Array of Numbers

Let's say we have an array of numbers that we want to loop through and perform a calculation on each number.

The for...of loop makes this a breeze:

let numbers = [10, 20, 30, 40, 50];
for (let number of numbers) {
  console.log(number * 2);
// Output:
// 20
// 40
// 60
// 80
// 100

Looping Through a String of Names

In the example below, we demonstrate how to loop over a string of names and format it in a specific way.

let names = "Gabe, Gleb, Gao, Greg";
let nameList = names.split(", ");
for (let name of nameList) {
  console.log(`Hello, ${name}!`);
// Output:
// Hello, Gabe!
// Hello, Gleb!
// Hello, Gao!
// Hello, Greg!

So, we first split the names into an array of individual names with the split() method. Then, we use the for...of loop to iterate over the nameList array and log a greeting for each name to the console.

let hobbies = ["painting", "reading", "traveling", "cooking"];
for (let hobby of hobbies) {
  console.log(`I enjoy ${hobby}.`);
// Output:

Combining for...of with Object Methods

The for...of loop can also be combined with object methods to iterate over object properties. For instance, the Object.entries() method can be used to return an array of an object's key-value pairs, which can then be looped over using a for...of loop.

let menu = {
  breakfast: 'eggs and bacon',
  lunch: 'grilled cheese',
  dinner: 'spaghetti'

for (let [key, value] of Object.entries(menu)) {
  console.log(`For ${key}, we're serving ${value}.`);
// Output:
// For breakfast, we're serving eggs and bacon.
// For lunch, we're serving grilled cheese.
// For dinner, we're serving spaghetti.

Here, we used the Object.entries() method to return an array of the menu object's key-value pairs. Then, we use array destructuring in the for...of loop to assign the key and value of each pair to separate variables, key and value. Finally, we log a statement to the console that displays each key-value pair.

Additional Resources

ECMAScript Specification for Iteration Statements

How to Read the ECMAScript Specification

The for Loop

The for...in Loop

The While Loop

The do...while Variation

Break and Continue in JavaScript