Loops
Why Loops?
Imagine you're a teacher and you need to write "Good job!" on 30 students' papers. You wouldn't write it by hand 30 times — you'd use a stamp. Loops are your code's stamp. They repeat a block of code as many times as you need.
JavaScript has several types of loops, each best suited for different situations:
for— when you know exactly how many times to loopwhile— when you loop until a condition becomes falsedo...while— like while, but guarantees at least one runfor...of— loop through values in an array (or any iterable)for...in— loop through keys/properties of an object
The Classic For Loop
While & Do...While
A while loop keeps going as long as its condition is true. It's like saying "keep stirring the soup while it's not boiling yet." Be careful — if the condition never becomes false, you get an infinite loop and your program freezes!
A do...while loop is almost the same, except it checks the condition after running the code. So the code inside always runs at least once — like a restaurant that lets you taste the food before deciding if you want more.
While & Do...While
For...Of and For...In
for...of is the modern, clean way to loop through arrays (and strings, Maps, Sets, etc.). It gives you the values directly — no need to mess with indexes.
for...in loops through the keys (property names) of an object. Be careful: for...in on arrays gives you index strings, not numbers, which can cause subtle bugs. Stick to for...of for arrays.