What is For…of Loop in JavaScript ?
Last Updated :
15 Feb, 2024
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) {
// code block to be executed
}
variable
: Represents a variable that will be assigned the value of each element in the iterable object during each iteration.
iterable
: Represents an iterable object (e.g., array, string, map, set) whose elements will be iterated over.
Example: Here, we have an array arr
containing numeric values. The for...of
loop iterates over each element of the array, assigning the value of each element to the variable value
, and then executes the code block inside the loop, which simply logs each value to the console.
Javascript
const arr = [1, 2, 3];
for (const value of arr) {
console.log(value);
}
|
Share your thoughts in the comments
Please Login to comment...