Let’s say you want to bounce a ball a few times. You might start by calling a function, bounceBall()
, like this:
This is fine for a few bounces, but what if you need a hundred? Writing bounceBall()
a hundred times is
impractical. Enter the for
loop!
Introducing the for
Loop
A for
loop lets you run a block of code multiple times. Here’s how you can bounce the ball ten times:
The structure of a for
loop is straightforward:
- initialExpression: Initialize the loop variable, usually
let i = 0
. - condition: Keeps the loop running as long as it’s
true
. - incrementExpression: Updates the loop variable, typically
i++
.
Breaking Down the Loop
Let’s dive into the loop’s components:
- Initialization:
let i = 0
sets the starting point. - Condition Check:
i < 10
keeps the loop going. - Execute Statement: Runs the code inside
{ }
- Increment:
i++
incrementsi
by one.
Here’s a practical example:
This loop runs twice, logging how many times the ball has bounced.
Beware of Infinite Loops
An infinite loop happens when the condition never becomes false
. For example:
This will hang your program. You may need to force quit your browser to stop it.
Looping Through Arrays
Often, you’ll loop through arrays:
The for...of
Loop
A cleaner way to loop through arrays is with the for...of
loop:
This loop is simpler and avoids manual indexing.
Wrapping Up
- Use a
for
loop to run code multiple times efficiently. for...of
loops provide cleaner syntax for arrays.- Avoid infinite loops by ensuring the condition can eventually become
false
.
Mastering loops will help you write more efficient and maintainable code. Happy coding!