What is the role of for-of loop in JS?

0 votes
26 views
Ravi Vishwakarma asked 8 days ago in Web Application by Ravi Vishwakarma

What is the role of for-of loop in JS?

1 Answer

0 votes
Ethan Karla answered 6 days ago by Ethan Karla
The for...of statement creates a loop iterating over iterable objects, including built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.
Syntax;
for (variable of iterable) {

  statement
}
variable
        On each iteration a value of a different property is assigned to variable. variable may be declared with const, let, or var.
Iterable
         Object whose iterable properties are iterated.
Array

const iterable = [10, 20, 30];
for (let value of iterable) {
  value += 1;
  console.log(value);
}
String

const iterable = 'boo';
for (const value of iterable) {
  console.log(value);
}
Map

const iterable = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (const entry of iterable) {
  console.log(entry);
}
for (const [key, value] of iterable) {
  console.log(value);
}
Set

const iterable = new Set([1, 1, 2, 2, 3, 3]);
for (const value of iterable) {
  console.log(value);
}
object

(function() {
  for (const argument of arguments) {
    console.log(argument);
  }
})(1, 2, 3);