Welcome to loops—your solution for repetitive tasks! Imagine needing to display 100 products from an array. Without loops, you would need 100 separate lines of nearly identical code.
Loops let you write the logic once and tell JavaScript to repeat it automatically.
Engagement Message
What's a repetitive task on a website that could be automated with a loop?
The for
loop is JavaScript's most common way to repeat code a specific number of times. It looks a bit complex at first, but it has three distinct parts inside its parentheses:
Let's break down what each part does.
Engagement Message
Can you guess what the three parts might control about how the loop runs?
Let's look at a real for
loop: for (let i = 0; i < 5; i++) { ... }
- Initialization:
let i = 0
creates a counter variablei
and starts it at 0. - Condition:
i < 5
is checked before each repetition. The loop continues as long as this is true. - Final Expression:
i++
runs after each repetition, increasing the counter by 1.
Engagement Message
