The Wayback Machine - https://web.archive.org/web/20240910040305/https://www.geeksforgeeks.org/javascript-for-of-loop/
Open In App

JavaScript for…of Loop

Last Updated : 30 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The JavaScript for…of loop is a modern, iteration statement introduced in ECMAScript 2015 (ES6). It allows developers to iterate over iterable objects such as arrays, strings, maps, sets, and more. It provides a simpler syntax compared to traditional for loops.

What is the for…of Loop?

The for…of loop iterates over the values of an iterable object, which is different from the for…in loop that iterates over the enumerable properties of an object.

Syntax:

for ( variable of Iterable ) {
    // Code block to be executed
}

Parameters:

  • variable: Represents the current value of each iteration from the iterable.
  • iterable: Any object that can be iterated over (e.g., arrays, strings, maps).

Examples of Using for…of Loop

1. Iterate Over an Array using for…of Loop

Arrays are one of the most common data structures in JavaScript. The for…of loop provides a concise way to iterate over array elements:

Example: The code initializes an array with values 1 through 5. It then iterates over each element of the array using a for…of loop, logging each element to the console.

JavaScript
const array = [ 1, 2, 3, 4, 5 ];

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

Output
1
2
3
4
5

2. Iterating Over a String using for…of Loop

Strings are also iterable objects in JavaScript. You can use the for…of loop to iterate over each character in a string.

JavaScript
const str = "Hello";

for (const char of str) {
    console.log(char);
}

Output
H
e
l
l
o

Code Explanation

  • str is the string you want to loop over.
  • Initiates the for...of loop, where char represents each character in the string during each iteration.
  • console.log(char) prints each character to the console during each iteration of the loop.

3. Iterating Over a Map using for…of Loop

Maps are a new data structure in ES6 that store key-value pairs. The for…of loop can be used to iterate over the entries of a map.

JavaScript
const map = new Map([
    ["name", "Akash"],
    ["age", 25],
    ["city", "Noida"]
]);

for (let [key, value] of map) {
    console.log(`${key}: ${value}`);
}

Output
name: Akash
age: 25
city: Noida

Code Explanation

  • First, we create a Map object where we want to iterate over.
  • Initiates the for...of loop, where [key, value] represents each key-value pair in the Map during each iteration.
  • Inside the loop, console.log(`${key}: ${value}`); prints each key-value pair to the console during each iteration of the loop.

4. Iterating Over a Set using for…of Loop

Sets are another new data structure in ES6 that store unique values. You can use the for…of loop to iterate over the elements of a set.

JavaScript
let set = new Set([1, 2, 3, 4, 5]);

for (let value of set) {
    console.log(value);
}

Output
1
2
3
4
5

5. Iterating Over an Object’s Properties using for…of Loop

While the for…of loop is not directly used to iterate over object properties, you can use it in combination with Object.keys(), Object.values(), or Object.entries() to achieve this.

JavaScript
let person = {
    name: "Akash",
    age: 25,
    city: "Noida"
};

for (let key of Object.keys(person)) {
    console.log(`${key}: ${person[key]}`);
}

Output
name: Akash
age: 25
city: Noida

The for…of loop in JavaScript provides a powerful and efficient way to iterate over iterable objects. Its syntax is simpler and more intuitive compared to traditional loops, making code easier to read and maintain. For more advanced JavaScript tutorials and examples, explore our JavaScript Tutorial and JavaScript Examples.

JavaScript for…of Loop – FAQs

What is a for-of loop in JavaScript?

A for-of loop is a control structure that allows you to iterate over the values of an iterable object, such as arrays, strings, maps, sets, and more. This loop is designed to traverse the values directly rather than the keys or indices.

What is the basic syntax of a for-of loop?

The basic syntax of a for-of loop includes the for keyword, followed by a variable to hold each value, the of keyword, and the iterable object to iterate over. The code block to be executed for each value is placed inside curly braces.

How does the for-of loop work?

The for-of loop iterates over the values of an iterable object. For each value, the loop assigns the value to the specified variable and executes the code block.

What is the difference between for-of and for-in loops?

for-of loop: Iterates over the values of an iterable object (such as arrays, strings, maps, etc.).

for-in loop: Iterates over the enumerable properties (keys) of an object.

Can a for-of loop be used with objects?

A for-of loop cannot be used directly with objects because objects are not inherently iterable. However, you can use a for-of loop in conjunction with Object.keys(), Object.values(), or Object.entries() to iterate over an object’s keys, values, or key-value pairs.



Previous Article
Next Article

Similar Reads

How to loop through HTML elements without using forEach() loop in JavaScript ?
In this article, we will learn how to loop through HTML elements without using the forEach() method. This can be done in the following ways: Table of Content Approach 1: Using the for loopApproach 2: Using the While loopApproach 3: Using the 'for.....of' statementApproach 4: Using the for...in statementApproach 1: Using the for loopThe HTML element
4 min read
How to Loop Through an Array using a foreach Loop in PHP?
Given an array (indexed or associative), the task is to loop through the array using foreach loop. The foreach loop iterates through each array element and performs the operations. PHP foreach LoopThe foreach loop iterates over each key/value pair in an array. This loop is mainly useful for iterating through associative arrays where you need both t
2 min read
How to Change Values in an Array when Doing foreach Loop in JavaScript ?
The forEach loop in JavaScript is one of the several ways to iterate through an array. ForEach method is different from all other looping methods as it passes a callback function for each element in the array. So, the possible approach to change the values in the array when doing foreach method in JavaScript, the method will not directly change the
3 min read
How to break nested for loop using JavaScript?
The break statement, which is used to exit a loop early. A label can be used with a break to control the flow more precisely. A label is simply an identifier followed by a colon(:) that is applied to a statement or a block of code. Note: there should not be any other statement in between a label name and associated loop. Example-1: Break from neste
3 min read
How to trigger setInterval loop immediately using JavaScript ?
This article will show some simple ways in which the setInterval() method can be made to execute the function without delay. There are many procedures to do so, below all the procedures are described with the example. Note: In this article setInterval() method will start immediately for the 1st time run. Below examples illustrate the above approach
2 min read
How to ignore loop in else condition using JavaScript ?
In this article, we will see the methods to ignore the loop in the else conditions using JavaScript. There are two ways to ignore the loop in the else condition: ContinueBreak Please see this, for explanations of the same. In simple terms, The Break statement exits out of the loop while the continue statement exits out of the particular iteration.
2 min read
What are the microtask and macrotask within an event loop in JavaScript ?
Event Loop: An Event Loop in JavaScript is said to be a constantly running process that keeps a tab on the call stack. Its main function is to check whether the call stack is empty or not. If the call stack turns out to be empty, the event loop proceeds to execute all the callbacks waiting in the task queue. Inside the task queue, the tasks are bro
4 min read
JavaScript SyntaxError - A declaration in the head of a for-of loop can't have an initializer
This JavaScript exception a declaration in the head of a for-of loop can't have an initializer occurs if the for -of loop contains an initialization expression like |for (var i = 0 of iterable)|. This is not valid initialization in for-of loops. Message: SyntaxError: for-of loop head declarations cannot have an initializer (Edge) SyntaxError: a dec
1 min read
How to Pause and Play a Loop in JavaScript using Event Listeners ?
Given below is a JavaScript program for DOM manipulation which is basically about How to Pause and Play a loop in JavaScript using event listeners (not to be confused with delay). In this article, we are using JavaScript with HTML so we need a web browser i.e., Chrome (recommended) or Electron Application. Pausing and playing a loop is such a diffi
4 min read
How to delay a loop in JavaScript using async/await with Promise ?
Given below is a JavaScript code snippet which is basically described how to delay a loop in JavaScript using async/await. In this article, we are using JavaScript either the web browser or Node.js. We all face a difficult situation in delaying a loop in JavaScript unlike C++ where we have sleep() function, but there is nothing like this in JavaScr
2 min read
Disadvantages of using for..in loop in JavaScript
In this article, we will see what are the disadvantages of using for..in loop and how to solve those issues. Disadvantages of using for..in loop: Reason 1: When you add a property in an array or object using the prototype and any other array arr that has no relation with that property when you iterate array x then you get that property. Example: Yo
2 min read
How to loop through a plain object with the objects as members in JavaScript ?
Looping through a plain JavaScript object with objects as members means iterating over each property of the object and accessing its values, which may also be objects. This is a common task in JavaScript, especially when dealing with JSON data or APIs. There are several ways to loop through a plain JavaScript object with objects as members. Here ar
3 min read
JavaScript for...in loop not working - Object property is not defined Error
A for...in loop is a special loop in JavaScript that enumerates all the keys (object property names) of an object. With each new iteration, a new property string is assigned to the loop variable. Error: Uncaught ReferenceError: Object property is not defined If we try to compare this loop variable with a non-string variable a ReferenceError is gene
3 min read
How to iterate an Array using forEach Loop in JavaScript?
Iterating through an array in JavaScript can be done in multiple ways. One of the most common methods is using the traditional for loop. In JavaScript, we have another modern approach to iterate the array which is by using the forEach method. This method is different from the traditional approach as it uses a functional approach. This approach prov
2 min read
Javascript Program For Finding The Length Of Loop In Linked List
Write a function detectAndCountLoop() that checks whether a given Linked List contains loop and if loop is present then returns count of nodes in loop. For example, the loop is present in below-linked list and length of the loop is 4. If the loop is not present, then the function should return 0. Recommended: Please try your approach on PRACTICE, b
3 min read
How to use async/await with forEach loop in JavaScript ?
Asynchronous is popular nowadays because it gives functionality of allowing multiple tasks to be executed at the same time (simultaneously) which helps to increase the productivity and efficiency of code. Async/await is used to write asynchronous code. In JavaScript, we use the looping technique to traverse the array with the help of forEach loop.
2 min read
Difference between forEach() and map() loop in JavaScript
When we work with an array, it is an essential step to iterate on the array to access elements and perform some kind of functionality on those elements to accomplish any task. For this loops like ForEach() and Map() are used. In this article, we are going to learn the difference between the forEach() and map() loops in JavaScript. JavaScript forEac
3 min read
JavaScript program to print Alphabets from A to Z using Loop
Our task is to print the alphabet from A to Z using loops. In this article, we will mainly focus on the following programs and their logic. Below are the loops used to print Alphabets from A to Z: Table of Content Using for loopUsing the while loopUsing a do-while loop Using for loopThe elements are iterated through a predetermined number of times
4 min read
What is the use of the for...in Loop in JavaScript ?
The for...in loop in JavaScript is used to iterate over the properties (keys) of an object. It allows you to loop through all enumerable properties of an object, including those inherited from its prototype chain. Syntax:for (variable in object) { // code to be executed}Example: Here, the for...in loop iterates over the properties of the person obj
1 min read
What is the use of the Break Statement in a Loop in JavaScript ?
The break statement in JavaScript is used to prematurely terminate a loop, allowing the program to exit the loop before the normal loop condition is met. It is often used to interrupt the loop execution based on certain conditions. Example: Here, the while loop will continue indefinitely (since the condition is true). However, the if statement insi
1 min read
How to Create a While Loop in JavaScript ?
In JavaScript, you can create a while loop using the while keyword followed by a condition. The loop continues to execute as long as the specified condition evaluates to true. Syntax:while (condition) { // Code to be executed while the condition is true // The condition is checked before each iteration}Example: Here, the loop continues to execute a
1 min read
How to Exit a Loop Before it Completes all Iterations in JavaScript ?
In JavaScript, you can exit a loop before it completes all iterations using the break statement. The break statement is used to terminate the loop prematurely based on a certain condition. Example: Here, the loop prints numbers from 1 to 10. However, when i becomes equal to 5, the break statement is executed, causing the loop to terminate immediate
1 min read
How to Push an Object into an Array using For Loop in JavaScript ?
JavaScript allows us to push an object into an array using a for-loop. This process consists of iterating over the sequence of values or indices using the for-loop and using an array manipulation method like push(), to append new elements to the array. We have given an empty array, and we need to push the object into the array. Below is an example
3 min read
Event Loop in JavaScript
In JavaScript, the event loop plays an important role in managing asynchronous operations and ensures the non-blocking behavior of the language. JavaScript is single-threaded, meaning it processes one task at a time and an event loop helps to handle asynchronous tasks efficiently. When an asynchronous operation, like a setTimeout callback or a user
1 min read
What is For...of Loop in JavaScript ?
In JavaScript, the for...of loop is a language construct used to iterate over elements of an iterable object, such as arrays, strings, maps, sets, and other data structures that implement the iterable protocol. It provides a more concise and readable syntax compared to traditional for loops or forEach() methods. Syntax:for (variable of iterable) {
1 min read
How to Write a While Loop in JavaScript ?
In JavaScript, a while loop is a control flow statement that repeatedly executes a block of code as long as a specified condition is true. Syntax:while (condition) { // code block to be executed while condition is true}The loop continues to execute the block of code within its curly braces ({}) as long as the specified condition evaluates to true.
1 min read
What is the fastest way to loop through an array in JavaScript ?
The fastest way to loop through an array in JavaScript depends upon the usecases and requirements. JavaScript has a large variety of loops available for performing iterations. The following loops along with their syntax are supported by JavaScript. Table of Content for loop while loop .forEach() loopfor...of Loopfor loop A JavaScript for loop compr
3 min read
How to Loop through XML in JavaScript ?
In JavaScript, looping over XML data is important for processing and extracting information from structured XML documents. Below is a list of methods utilized to loop through XML. Table of Content Using for loop with DOMParser and getElementsByTagNameUsing Array.from with DOMParser and childNodesUsing for loop with DOMParser and getElementsByTagNam
2 min read
JavaScript Program to Remove Loop in a Linked List
A linked list is a collection of nodes that contain both a data element and a reference (or pointer) to the next node in the collection. A common concern with linked lists is having loops and cycles. When one of the nodes in the linked list points towards any of its previous nodes leading to an infinite cycle. While traversing the list, this can ca
7 min read
How to add a delay in a JavaScript loop?
JavaScript doesn't offer any wait command to add a delay to the loops but we can do so using setTimeout method. This method executes a function, after waiting a specified number of milliseconds. Below given example illustrates how to add a delay to various loops: For loop:[GFGTABS] JavaScript for (let i=0; i<10; i++) { task(i); } function task(i
3 min read