Loops
A loop repeats code. Instead of writing console.log 100 times, you write it once and loop 100 times. Loops are how programs process every item in a list, every row in a file, or every user in a database.
The for loop
A for loop has three parts, separated by ;:
- Start:
let i = 1runs once, before the loop begins. - Condition:
i <= 5is checked before every lap. The loop stops when it's false. - Step:
i++runs after every lap.
Looping over a list: for...of
This is the most common loop in modern JavaScript.
The while loop
Use while when you don't know in advance how many laps you need.
Infinite loops: if the condition never becomes false, the loop runs forever. This site stops your code after a few seconds, but in a real program it would freeze. Always make sure something inside the loop moves it toward the end.
break and continue
breakexits the loop completely.continueskips to the next lap.
Building results with loops
A very common pattern: start with an empty value and build it up.
Nested loops
Practice: FizzBuzz
The classic interview warm-up. Print the numbers 1 to 20, but print Fizz for multiples of 3, Buzz for multiples of 5, and FizzBuzz for multiples of both.
1.How many times does for (let i = 0; i < 3; i++) run?
2.Which loop is best for going through every item in an array?