Last time, we saw that repeating tasks is tedious. JavaScript gives us tools for this, and the first one we'll learn is a type of for
loop.
Engagement Message
Ready to see how it works?
The for...of
loop is perfect for repeating an action for each item in a collection, like an array.
It's like saying, "For each student in my class list, hand them a book."
Engagement Message
Make sense?
If you have an array like let myItems = ["pen", "book"];
, a for...of
loop will run two times—once for "pen"
and once for "book"
.
Engagement Message
If an array has 3 items, how many times does the loop run?
Before we see the loop structure, let's learn about a new keyword: const
.
You already know let
creates a variable that can be changed later. const
creates a variable that cannot be reassigned once it's set - it's constant.
In loops, we use const
for the loop variable because it gets a new value automatically in each iteration, but within each single loop cycle, that value shouldn't change.
