HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Loop For Of

The for...of statement loops through the values of an iterable object. It works for built-in iterables like Arrays, Strings, Maps, NodeLists, and more.


Iterable Iteration Syntax

In each iteration, the value of the next property is assigned to the variable.

for (variable of iterable) {
  // code block to be executed
}

Case Study 1: Looping over an Array

Unlike for...in, this gives you the actual values directly.

const cars = ["BMW", "Volvo", "Saab"];

for (let x of cars) {
  console.log(x); // BMW, Volvo, Saab
}

Case Study 2: Looping over a String

You can use for...of to loop over each character in a string.

let language = "JavaScript";

for (let x of language) {
  console.log(x); // J, a, v, a, s, c, r, i, p, t
}

for...in vs. for...of

Understanding the difference between these two loops is critical for writing clean JavaScript:

  • for...in iterates over the property names (keys).
  • for...of iterates over the property values (data).
When to use which? Use for...in for Objects. Use for...of for Arrays, Strings, and Sets/Maps.

Key Points to Remember

  • for...of is for iterating over iterable values
  • It provides a much cleaner syntax for arrays than a traditional for loop
  • The loop variable represents the value, not the index
  • It works perfectly with modern data structures like Sets and Maps
  • Does not work on regular objects (use for...in for those)
  • It is an ES6 feature, modern and highly readable