ES6 introduced a new type of loop statement for of loop in JavaScript. This new loop works with iterable objects.
Iterable objects are arrays, strings, sets, and maps that represent a sequence or set of elements. Other iterable objects are array-like objects (e.g., arguments or NodeList), and user-defined iterable objects.
For…of loop in JavaScript allows us to loop or iterate through values of an iterable object. In other words, for of loop provides another way to loop over elements in a collection.
The general syntax to define for…of loop statement in JavaScript program is as:
for (variable of iterable) { // code block to be executed }
Superficially, the syntax looks like for…in loop. In the above syntax, the for keyword is followed by parentheses that contain details about what loop has to do.
The parentheses contain a variable declaration followed by the of keyword and an iterable object like array, set, strings, etc.
Consider the following example where we have used for of statement to loop through elements of an array of numbers. We will compute their sum.
Program code 1:
<script> // Creating an array. let nums = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]; let sum = 0; // Using for of loop statement. for(let element of nums) { sum += element; } document.write(sum); // output: 550 </script>
In the above script code, the body of loop executes for each element of nums array. Before each execution of the loop body, the next array element is assigned to the variable named element. The elements of the array are iterated in order from first to last.
JavaScript For of loop with Array (Iterating over Array)
For…of loop in JavaScript is a superb choice when we need to loop or iterate over an array. Let’s create a JavaScript program in which we will iterate over an array.
Program code 2:
<script> // Creating an array. const fruits = ["Banana", "Apple", "Orange", "Guava", "Mango"]; // Using for of loop statement. for(const element of fruits) { document.write(element, "<br>"); } </script>
Output: Banana Apple Orange Guava Mango
In this example, we have used for of loop statement to loop over an array. Using for of loop, we cannot know the index number of each element. If you need to know the indexes, then use normal for loop. Look at the following script code.
Program code 3:
<script> // Creating an array. const fruits = ["Banana", "Apple", "Orange", "Guava", "Mango"]; // Using for loop statement. for(let i = 0; i < fruits.length; i++) { document.write(`${i + 1}: ${fruits[i]}`, "<br>"); } </script>
Output: 1: Banana 2: Apple 3: Orange 4: Guava 5: Mango
We can also use for in loop statement to iterate over elements of an array with indexes. Glance at the following code to understand better.
Program code 4:
<script> // Creating an array. const fruits = ["Banana", "Apple", "Orange", "Guava", "Mango"]; // Using for in loop statement. for(let fruit in fruits) { document.write(`${fruit}: ${fruits[fruit]}`, "<br>"); } </script> </body> </html>
Output: 0: Banana 1: Apple 2: Orange 3: Guava 4: Mango
JavaScript For of loop with Objects (Iterating over Objects)
Objects are non iterable by default. Trying to use for…of statement on a regular object throws a TypeError at runtime. For example:
<script> // Creating an object with properties. let x = {a: 10, b: 20, c: 30, d: 40}; for(let element of x) // throws TypeError because x is not iterable. { document.write(element); } </script>
So, how do we iterate over them? If we want to loop or iterate over properties of an object, we can use for…in loop in JavaScript, or use for…of loop with Object.keys() method. Let’s write code for it.
Program code 5:
<script> // Creating an object. let x = {a: 10, b: 20, c: 30, d: 40}; let keys = ""; for(let k of Object.keys(x)) { keys += k; } document.write(keys); </script>
Output: abcd
In the above code, Object.keys() method returns an array of properties names for an object, and arrays are iterable with JavaScript for of loop.
We can also iterate through their associated values like this if we do not want to iterate over keys of an object. Let’s write code for it.
Program code 6:
<script> let x = {a: 100, b: 200, c: 300, d: 400}; let sum = 0; for(let v of Object.values(x)) { sum += v; } document.write("Sum: " +sum); </script>
Output: Sum: 1000
ES6 introduced Object.entries() function that we can use with for of loop to iterate over both keys and values of an object’s properties. Let’s write code for it to understand more clearly.
Program code 7:
<script> let capitals = { US: "Washington, D.C.", India: "New Delhi", Australia: "Canberra", Russia: "Moscos", Canada: "Ottawa" }; let elements = ""; for(let [k, v] of Object.entries(capitals)) { elements += k + ": " + v + "<br>"; } document.write(elements); </script>
Output: US: Washington, D.C. India: New Delhi Australia: Canberra Russia: Moscos Canada: Ottawa
The function Object.entries() returns an array of arrays, where each inner array represents a key/value pair for one property of an object.
For of with Strings (Iterating over Strings)
In ES6, Strings are iterable character by character. A string is a sequence of Unicode characters that are iterated by Unicode codepoint, not by UTF-16 character.
Let’s take an example program where we will loop over a string character by character.
Program code 8:
<script> let string = "Tech"; for(let str of string) { document.write(str, "<br>"); } </script>
Output: T e c h
Iterating over Set objects using for of loop
Set class is iterable in ES6. When we iterate over elements of set with for…of loop, then the body of loop runs for each element of set. Let’s take a simple example program where we will iterate over elements of set.
Program code 9:
<script> // Creating a Set with elements. let set = new Set([10, 20, 30]); // Looping over elements of Set using for of loop. for (let i of set) { document.write(i+ "<br>"); } </script>
Output: 10 20 30
Iterating over Map objects
In ES6, Map class is iterable. The iterator for a Map object does not iterate over the Map keys, or Map values, but key/value pairs.
Before each iteration of loop body, the iterator returns an array whose first element is key and whose second element is the corresponding value. Let’s create a simple JavaScript program to iterate over map objects.
Program code 10:
<script> // Creating map object. let map = new Map(); // Adding elements into the map. map.set('f<irstName', 'Tripti'); map.set('age', '22'); // Iterating through Map. for (let [key, value] of map) { document.write(key + ': ' + value, "<br>"); } </script>
Output: firstName: Tripti age: 22
Difference between for…of and for…in loops in JavaScript
1. for…of loop was introduced in ES6, whereas for…in loop introduced in ES5.
2. The for…in loop iterate through the keys of an object. In other words, for…in loop returns a list of keys. For example:
let list = [10, 20, 30]; // for...in loop returns a list of keys. for(let x in list) { console.log(x); // output: o, 1, 2. }
The for…of loop iterates through the values of an iterable. For example:
let list = [10, 20, 30]; // for...of loop returns the values. for(let x of list) { console.log(x); // output: 10, 20, 30. }
3. The for…of loop cannot be used to iterate over an object. Whereas, we can use for…in to loop over an iterable such as arrays and strings, but we should avoid using for…in for iterable objects.
Note: Some browser may not support for…of loop introduced in ES6. To know more, visit JavaScript for…of support.
Try It Yourself
Program code 11:
<script> let people = ["Tripti", "Ivaan", "John"]; for(let person of people) { document.write(person); } </script>
In this tutorial, you learned for…of loop in JavaScript with example program. Hope that you will have understood the basic concept of for of loop and how to use it.
Thanks for reading!!!
Next ⇒ Passing array to function in JavaScript⇐ Prev Next ⇒