|

Using "for...of" in JavaScript

Using "for...of" in JavaScript Photo by Etienne Girardet on Unsplash

How to use the for...of loop in JavaScript

The for...of statement in JavaScript performs a loop operation that works on a sequence of values from an iterable object. Iterable objects include structures like Array, String, Map, Set, and more.

The syntax works as follows:

for (let city of cities) {
  console.log(city);
}

In this case, city will be the variable that holds the individual value of each item in the cities iterable. You can use let, const, var, previously declared variables, or even other ways to declare the variable.

cities needs to be an iterable, as described earlier, otherwise, the loop will not execute as expected. To better understand iterable objects, refer to the specific “Built-in iterables” section of the MDN article.

Describing the operation

The loop occurs individually, one by one, in sequential order, as with other types of loops in JavaScript.

You can interrupt an iteration using the break command or skip an iteration with the continue command, just as in other loops in JavaScript again.

Now let’s iterate over a String directly:

const word = "wow!";

for (const letter of word) {
  console.log(letter);
}
// "w"
// "o"
// "w"
// "!"

Iterating over Array

const anArray = ['a', 'b', 'c'];
for (let item of anArray) {
  console.log(item);
  // a
  // b
  // c
}


Iterating over Map

const sampleMap = new Map([
  ["1", "a"],
  ["2", "b"],
  ["3", "c"],
]);

for (const item of sampleMap) {
  console.log(item);
  // ["1", "a"]
  // ["2", "b"]
  // ["3", "c"]
}

Iterating over Set

const ourSet = new Set('LetterOccurrence');
for (let item of ourSet) {
  console.log(`${item} is one of the unique letters in our 'LetterOccurrence' string`);
  // "L is one of the unique letters in our 'LetterOccurrence' string"
  // "e is one of the unique letters in our 'LetterOccurrence' string"
  // "t is one of the unique letters in our 'LetterOccurrence' string"
  // "r is one of the unique letters in our 'LetterOccurrence' string"
  // "O is one of the unique letters in our 'LetterOccurrence' string"
  // "c is one of the unique letters in our 'LetterOccurrence' string"
  // "u is one of the unique letters in our 'LetterOccurrence' string"
  // "n is one of the unique letters in our 'LetterOccurrence' string"
}

The for...of loop in JavaScript allows us to perform loops in a more practical and concise way, enhancing the readability and clarity of our code. Were you already familiar with and using this feature?

I hope this article helped and encouraged you to use this type of loop in JavaScript. Until next time! 👋