JS For Of Loop

JavaScript for...of Loop

There is another loop we can use to easily iterate over the elements of an array (or other iterable objects): the for...of loop.

While it cannot be used to directly change the value associated with the index as we can do with a regular for loop, it is an incredibly clean and readable loop for processing values.

Syntax of the for...of Loop

Here is what the syntax looks like:

let arr = [some array];

for (let variableName of arr) { // code to be executed // value of variableName gets updated every iteration // all values of the array will be variableName once }

You can read it like this: "For every value of the array, call it variableName and do the following."


Example: Iterating Over an Array

Let's look at how we can log the values of a names array using this loop:

for...of Loop Example

let names = ["Chantal", "John", "Maxime", "Bobbi", "Jair"];

for (let name of names) { console.log(name); }

Code Explanation

We need to specify a temporary variable; in this case, we called it name. This temporary variable is used to hold the value of the current iteration.

After the iteration completes, it automatically grabs the next value in the array. This goes on until every item in the array has been processed, resulting in an output of all the names listed sequentially.


Advantages and Limitations

The for...of loop is an excellent tool, but it is important to know when to use it over a standard for loop.

Limitations

Advantages


Exercise

?

What is one of the main advantages of using a for...of loop instead of a traditional for loop to read an array?