Open In App
Related Articles

JavaScript for…of Loop

Improve Article
Improve
Save Article
Save
Like Article
Like

JavaScript for of statement iterates over the values of an iterable object (like Array, Map, Set, arguments object, …,etc), executing statements for each value of the object.

JavaScript for of loop makes it easy to loop through the elements without needing to handle the index or iteration logic which makes the code short and easier to understand.

Syntax:

for ( variable of iterableObjectName) {
...
}

 Example 1: The following snippet demonstrates the for..of loop over an array.

Javascript




// Array of numbers
let numArray = [1, 4, 16, 25, 49];
 
console.log("Elements of numArray are->");
 
// for...of Loop
for (let value of numArray) {
    console.log(value);
}


Output

Elements of numArray are->
1
4
16
25
49

Example 2: The following snippet demonstrates the for..of loop over a string.

Javascript




// String object
let st = "Geeksforgeeks";
 
// for..of loop
console.log("Elements of string st are->");
for (let value of st) {
    console.log(value);
}


Output

Elements of string st are->
G
e
e
k
s
f
o
r
g
e
e
k
s

Example 3: The following code demonstrates the for..of loop over an argument object.

JavaScript arguments is an object which is local to a function.  It acts as a local variable that is available with all functions by default except arrow functions in JavaScript. 

Javascript




// Iterating over argument objects
function Geeks() {
    for (let value of arguments) {
        console.log(value);
    }
}
 
// Iterating over all arguments passed
// through the function
Geeks("Geeks", "for", "Geeks");


Output

Geeks
for
Geeks

Example 4: The following code demonstrates the for..of loop over an argument objects

Javascript




// Map is an object that takes key-value pair as input
let mapObject = new Map([
    ["Geeks", 1],
    ["For", 2],
    ["geeks", 3],
]);
 
console.log("Display of Key-Value Pair->")
for (const entry of mapObject) {
    console.log(entry);
}
 
console.log("Display of Value only->")
for (const [key, value] of mapObject) {
    console.log(value);
}


Output

Display of Key-Value Pair->
[ 'Geeks', 1 ]
[ 'For', 2 ]
[ 'geeks', 3 ]
Display of Value only->
1
2
3


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 20 Nov, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials