How to use the for…of Statement in JavaScript

  • 7 min read
  • December 2, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

The for…of statement was introduced in ECMAScript2015 (ES6) and adds a powerful new type of loop to JavaScript.

JavaScript offers many different types of loops, each of which enables you to repeatedly execute a function or block of code.

The for…of statement is a very powerful for three reasons:

  1. It can loop through any iterable object – these include Strings, Arrays, array-like-objects, Maps, Sets, DOM collections, and more. Note that while this article will provide you with the required tools to apply the for…of statement to multiple different cases, we will not cover all object types in detail.
  2. Contrary to Array iteration methods (like map, forEach, filter, etc.), the for…of statement allows use of the break and continue statements, giving you more control over the iteration.
  3. Its syntax is fairly simple.

A basic for…of statement example

Below is a basic example illustrating how to use the for…of statement:

const nums = [1, 2, 3, 4];
for (let num of nums) {
    console.log(num * 3);
}
// Expected output:
// 3
// 6
// 9
// 12

In the example above, the for…of statement iterates over the nums array and multiplies each number (num) in the array by 3.

This is very similar to the Array forEach() iteration method. Below is an equivalent block of code written using forEach(), for comparison:

nums.forEach(num => console.log(num * 3))

 

Syntax

The syntax of the for…of statement is as follows:

for (variable of iterable) {

function or code block for execution

}

variable: on each iteration this variable will be assigned the value of the element currently being processed. This variable can be declared with const, let, or var.

iterable: an object with iterable properties.

Remember that everything in JavaScript is an object, including Strings, Numbers, and functions. This allows all of these types to have properties and methods.

Let’s explore the syntax in more detail with another example:

const str = 'codota';
for (let char of str) { console.log(char.toUpperCase()); }
// C
// O
// D
// O
// T
// A

In the above code, the for…of statement is applied to a String (const str). In this example the string is the iterable object.

let char defines the variable . In each iteration of the loop, the value of this variable changes based on the current portion of the string being processed – it begins with ‘c’, and progresses through all of the letters of the string until the loop ends with let char = ‘a’.

In the above loop, each letter in the original string is converted to an uppercase character, then printed to the console.

Using the for…of statement with the element’s index

In order to retrieve the index of an element along with its value, you will need to apply the entries() method to the iterable object being looped through. This method returns a new Array Iterator object that contains the key-value pairs of each element in the array. Retrieving and working with these values requires the use of destructuring assignment – this allows you to extricate specific values from an array.

const nums = [1, 2, 3, 4];
for (let [index, num] of nums.entries()) {
    console.log(num * index);
}
// Expected output: 
// 0
// 2
// 6
// 12

Let us explore the above example step-by-step

We start by declaring const nums, which points to an Array containing four numbers (1, 2, 3, 4)

The for…of statement is applied to the return value of nums.entries(), and not the array nums! This return value is an Array Iterator object.

Note: If we fail to use the entries() method, iteration of this type would not be possible. JavaScript would return the error Uncaught TypeError: .for is not iterable.

In order to provide value to both of the variables being used by this loop, we group them together using square brackets. This indicates the use of destructuring assignment.

With the above elements in place, it’s now possible to use both the index and the value of each item in the nums array. Note that because JavaScript arrays begin their indices at zero, the result of the first multiplication operation is also zero.

Implementing break / continue statements in for…of

The break and continue statements are powerful tools for controlling the flow of code in a loop.

The break statement is used to break out of the loop and end the iteration process.

The continue statement is used to skip past one iteration of the loop.

Let’s explore this with another example:

const nums = [1, 2, 3, 4];
for (let [index, num] of nums.entries()) {
    if (num === 3) continue;
    console.log(num * index);
}
// Expected output: 
// 0
// 2
// 12

In the example above, the code is identical to the previous example with one difference – the continue statement. According to the continue statement above, if the value of the num variable is strictly equal (===) to 3, the code will skip this iteration. That is why the result 6 is missing from the above results.

If the break statement was used in place of the continue statement, the iteration process would have ended after the second iteration, with only the first two results being printed to the console.

Applying the for…of statement to Objects

JavaScript objects are not iterable. The most common way to loop through an object’s properties is by using the for…in statement.

Looping through an object’s properties can also be accomplished using the for…of statement. Doing so requires using the Object.entries() method, which operates differently for objects, along with destructuring assignment. An example is provided below:

const scores = { Danny: 12, Michelle: 16, Tim: 7, Naomi: 13, Dwyane: 10 };
for (const [name, value] of Object.entries(scores)) {
    console.log(`${name}` + ' scored ' + `${value}` + ' points');
}
// Expected output:
// Danny scored 12 points
// Michelle scored 16 points
// Tim scored 7 points
// Naomi scored 13 points
// Dwyane scored 10 points

Once again, let’s explore the operation above step-by-step.

We begin by declaring a new variable – const scores. This variable points to an Object containing players’ names and their scores.

The for…of statement is applied to the return value of Object.entries(scores), and not the object scores! The Object.entries() method returns an array whose items are arrays as well. Each array is a [key, value] pair. The key is a string corresponding to the current object property being worked with, and the value is the value of the matching property.

In the above example, the return value of Object.entries(scores) is

[ [“Danny”, 12], [“Michelle”, 16], [“Tim”, 7], [“Naomi”, 13], [“Dwyane”, 10] ]

This is clearly an iterable object.

The square brackets surrounding the name and value variables indicate the use of destructuring assignment. At each iteration, the destructuring assignment extricates the property name and value from each array. With this completed, it is now possible to use both variables and print them to the console.

While at the beginning of this article we mentioned that the for…of statement can be used to iterate over any iterable object, sometimes additional steps are required to make a given object iterable. This is demonstrated in the example above, allowing us to turn a non-iterable object into something that we can loop through.

 

Other frequently used loops

There are several other types of loop statements in JavaScript that can be used in addition to for…of statements. These include:

  • for statement
  • for…in statement (used to loop through Objects)
  • do…while statement
  • while statement
  • various iteration methods for JavaScript Arrays.

 

Related Articles

JavaScript – How to Use for Statements

JavaScript – How to Use the for…in Statement

JavaScript – How to Use Array reduce method

Related Posts

How to Change CSS Using JavaScript

How to Change CSS Using JavaScript

Cascading Style Sheets (CSS) is used to design the layout of a webpage. CSS is a set of structured rules describing the layout of elements in

How to Use the Assignment Operator in JavaScript

How to Use the Assignment Operator in JavaScript

The Assignment operator is used to assign a value to a variable. Assignment (=) The assignment operator simply assigns the value of the right operand to

How to Use the for…in Statement in JavaScript

How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties. Basic for…in loop example The following code demonstrates a basic example using the for…in statement