π JavaScript Loops β Made Easy (and Real!)
Ever find yourself copying and pasting the same line of code over and over? Loops are here to save your fingers (and your sanity). In JavaScript, loops let you repeat a block of code without writing it multiple times. Think of them like a playlist on repeat β you set it once, and it keeps going.
πΉ for Loop β When You Know How Many Times
Use a for loop if you know how many times something should repeat. Hereβs an example:
for (let i = 1; i <= 5; i++) {
console.log("Step " + i);
}
This prints:
Step 1
Step 2
Step 3
Step 4
Step 5
Itβs like saying, βHey JavaScript, do this 5 times, please.β
πΉ while Loop β When Youβre Not Sure Yet
If youβre not certain how many times the code should run, but you want it to keep going while a condition is true, then go for a while loop.
let count = 1;
while (count <= 3) {
console.log("Count is: " + count);
count++;
}
Here, the loop checks the condition first. If itβs true, it runs the block. If not, it skips it.
πΉ do...while Loop β Run At Least Once
This one guarantees at least one run β even if the condition is false. Itβs great when you want something to happen first, then decide whether to keep going.
let number = 1;
do {
console.log("Number is: " + number);
number++;
} while (number <= 2);
Even if the condition fails after the first run, the block still executes once.
π TL;DR β Loop Logic Recap
- for β Use when you know how many times you want to loop.
- while β Use when you want to loop while a condition is true.
- do...while β Use when you need to run first, check later.