For Loops
๐จโ๐ผ When you need to repeat code a specific number of times, the
for loop is
your tool of choice.The syntax:
for (initialization; condition; update) {
// code to repeat
}
For example:
for (let i = 0; i < 5; i++) {
console.log(i) // Logs 0, 1, 2, 3, 4
}
The three parts:
- Initialization (
let i = 0) - Runs once before the loop starts - Condition (
i < 5) - Checked before each iteration; loop stops when false - Update (
i++) - Runs after each iteration
- Write a for loop that logs numbers 1 through 5
- Write a for loop that logs even numbers from 2 to 10
- Write a for loop that counts down from 5 to 1
๐ฐ To count by 2s, use
i += 2 in the update. To count down, start high and use
i--.