Lesson 2 - for..of

Before we get into explaining the magic of the directive *ngFor, first let's go over the variant of the for loop known as for..of, as you will be seeing it in future lessons. If you're already familiar with it, feel free to skip ahead.

Standard for loop vs. for..of

Let's say we have the following array:

const colors = ['orange', 'purple', 'yellow', 'pink', 'blue']

The object is to use a loop to console log each color. Lets view both the standard method as well as using for..of so you can see them side by side

Using for..of

for (let color of colors) {

console.log( color );

}

Now this may be new to you. We are looking through the array colors, and we will execute the code inside the loop for every item that is inside that array. We have declared a variable named color that will hold the value of each item in the array as we run through the loop.

Much like the old way, the name color is arbitrary; we could have named it bicycle and that would be fine, as long as we made sure that when we referred to the item in the array that we are going over, we used the correct name of the variable we declared

Also like the old way, the name of the array we are going through, colors is NOT arbitrary; we are going through an array that we have already given a name to, so we must refer to it by it's proper name.

The easiest way to remember the for..of loop is that its is going to execute the code inside the loop oince for each value inside the array.

Summary

Each method will return the same thing. One thing you may not have known is that using for..of is part of ES6, meaning if you want to use it in Javascript, you can!

There are other variants of iterating through an array that you may have used such as for..in, and .forEach(). They both have their uses, we're going over for..of because it's what you will see in Angular when we utilize *ngFor.

Wait, I noticed that for..of isn't passing the value of the index? What if I want to use that index? I love indexes!

Odd love of indexes aside, yes, there is a way to do it. I'm not going over it here because they way to do it in JS is different than how it will look using *ngFor, so we will go over it... in the next lesson.

References

You know... in case you wanna read more.

MDN page for for..of

A nice description of all the ways to go over an array by Ben Ilegbodu