05. Loops & Iteration
Explanation
Loops provide a way to repeat a specific block of code multiple times without writing the same lines over and over again.
The `for` loop is the most versatile, consisting of an initializer, a condition, and an increment/decrement expression.
`while` loops are better suited for scenarios where you don't know exactly how many iterations you need beforehand.
In modern JS, we often use `for...of` for arrays or `.forEach()` for simple iteration, though `for` remains the fastest.
Infinite loops are a common pitfall; always ensure your exit condition will eventually evaluate to false to avoid crashes.
Efficient iteration handles large datasets quickly and is a fundamental skill for any developer working with complex data.
Example
for (let i = 0; i < 5; i++) { ... }Exercise Task
Write a 'for' loop that logs the numbers from 5 down to 1 (countdown).
script.js
1
2
// Start loop here
Console
Click "Run" to execute your code...