JavaScript
Tutorial: loops in JavaScript - repeat tasks without losing your mind
Learn for and while by creating a list of repeated greetings without copy-pasting code.
If you've ever copy-pasted the same line of code ten times, changing only a number, congratulations: you just (badly) reinvented the loop. Let's do it properly today.
Step 1: the for loop
for (let i = 1; i <= 5; i++) {
console.log(`Repetition number ${i}`);
}
A for has three parts separated by semicolons: where it starts (let i = 1), how long it continues (i <= 5), and what changes on each pass (i++, which adds 1). The result: five printed lines without writing console.log five times.
Step 2: loop over an array with for
const names = ['Ana', 'Luis', 'Sofia'];
for (let i = 0; i < names.length; i++) {
console.log(`Hi, ${names[i]}!`);
}
names.length gives you the array's size, so the loop stops exactly where it should, no manual counting (or risking an embarrassing "undefined").
Step 3: the while loop
let attempts = 0;
while (attempts < 3) {
console.log(`Attempt ${attempts + 1}`);
attempts++;
}
while repeats the block while the condition is true. It's perfect when you don't know in advance how many times it'll repeat (for example, "until the user guesses the number").
Watch out for this
// while (true) { console.log('this never stops'); }
If you forget to update the variable controlling the condition, your loop never ends and your browser freezes. We've all done it at least once (well, technically at least once a week).
What did you just learn?
- How to repeat code with
forandwhile. - How to loop over an array using its
.length. - Why an infinite loop is a bug, not a feature.