for...of

The for...of construct is used to iterate over an iterable object. Natively provided iterable objects include StringArrayTypedArray, Mapand Set. Syntactically, for...of shares the characteristics of for...in:

for (LeftSideAssignment in IterableObject) IterationBody

The purpose of each part is as follows: 

  • LeftSideAssignment can be anything that would be valid on the left side of an assignment expression and is evaluated within the scope of IterationBody on every new iteration
  • IterableObject can be any expression that evaluates to an iterable object—in other words, anything that implements [Symbol.iterator] as a method
  • IterationBody is any single-line or block statement

An idiomatic for...of usage may look like this:

const array = [1, 2, 3];

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

// Logs: 1, 2, 3

Since its introduction into the language, for...of has become the most idiomatic way to loop over arrays, replacing the previously idiomatic for (var i = 0; i < array.length; i++) {...} pattern.

The scoping behavior of let, var, and const is identical to that described in the last section on for...in. It is advisable to use const as it will initialize a fresh and immutable variable for each iteration. Using let is not awful but, unless you have a specific reason to need to mutate the variable yourself within IterationBodyyou'll be better off using const.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.150.231