JavaScript for...of Loop

Subject: JavaScript

The for...of loop in JavaScript allows you to iterate directly over the values of iterable objects like arrays, strings, maps, sets, and more. It’s more readable and efficient when you don’t need the index or key.


Syntax

  • variable: Local variable that holds the current value.
  • iterable: Any object implementing the iterable protocol.

Example 1: Looping Through an Array


Example 2: Looping Through a String


Example 3: Looping Through a Set


Example 4: Looping Through a Map


for...of vs for...in

Featurefor...offor...in
Iterates OverValues of iterablesKeys of objects
Use CaseArrays, strings, sets, mapsPlain objects
ReturnsValueProperty name (key)
Recommended ForValue-based iterationObject property iteration

Key Takeaways

  • for...of is ideal for value-based iteration on iterable objects.
  • Works with: arrays, strings, sets, maps, arguments, etc.
  • Does not work with plain objects.
  • Use destructuring when looping over Maps or arrays of pairs.
  • Prefer for...of when you don't need an index, just the value.
Next : JS Functions