for...of LoopThere 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.
for...of LoopHere 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."
Let's look at how we can log the values of a names array using this loop:
let names = ["Chantal", "John", "Maxime", "Bobbi", "Jair"];for (let name of names) { console.log(name); }
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.
The for...of loop is an excellent tool, but it is important to know when to use it over a standard for loop.
i = 0, i = 1) inside the loop.for...of loop is safety. You cannot accidentally get stuck in an infinite loop, and you cannot accidentally skip values. It will always run exactly once for every element.for (let i = 0; i < arr.length; i++) loop.What is one of the main advantages of using a for...of loop instead of a traditional for loop to read an array?