logo

NJP

The For…Of Loop - Let's Learn ECMAScript 2021 with Earl Duque

Import · Jan 25, 2024 · video

In this lesson. It's one of my favorite ones. We're going to be learning
a new way to do loops. So if I have a list of incidents, this array of incidents,
one of the ways I could iterate through it is you should all know this one for let id in incidentIds, and then you access it by saying incidentIds and then the actual index
that you're iterating through. If I press run script, there it is. One, two, three. Perfect. But this gets a little bit complicating. If you, for instance,
have a nested loop, so what if it looks like this and then instead each of these were itself a array of its own. So now if I want to iterate
through each of those, I can say let ID two in incidents. IDs ID, and then it gets further complicating in there
when I actually want to log things because now I have to say incidents, incident IDs, I.D. ID two. So if I run this, yeah, it works. But what if I keep getting further
and further down? This syntax becomes almost untenable. So to simplify things,
what we can use instead of this for...in loop,
we can actually use for...of loop. So in this we say for of instead and we can get rid of this whole thing
and just use id. and so instead of id being an index to help you identify
what index you're on in the array, id takes on the form of that element itself. And so if I press run
script one, two, three, so id itself is each element
inside of the array. this can be pretty useful if you know,
you don't need the index at all. So if you don't need the index
in your script at all, why use it? That's what for...of loops are useful for. The other thing that they're useful
for is iterating through strings. So if I have a string called status and it is set to the word resolved,
if I use the for...of loop on this. So for letter of status, you can actually iterate through
the entire string one letter at a time, there you go. R E S O L V E D find out what it means to me. R-E-S-P-E-C-T.

View original source

https://www.youtube.com/watch?v=FLPpstjs_Is