In Js, Some piece of codes are repeatative and need to call frequently.
We can not write same lines of code multiple times. if we do then its hard to change or debug all together.
to avoid this issue, there are many Loops to use in js.
Loops are repeaters. it repeats the line of code as we need.
Instead of this,
console.log("Hello");
console.log("Hello");
console.log("Hello");
console.log("Hello");
console.log("Hello");
We can write it as this,
for (let i = 0; i < 5; i++) {
console.log("Hello");
}
Use when you know how many times to repeat.
Let's take above example,
console.log("Hello");
console.log("Hello");
console.log("Hello");
console.log("Hello");
console.log("Hello");
We can write this as,
for (let i = 0; i < 5; i++) {
console.log("Hello");
}
this is most simple way to get repeatative output.
Use when: We repeat until something happens .
This is conditional loop
Let's take above example,
let num = 0;
while (num < 3) {
console.log(num); // 0, 1, 2
num++;
}
Console Output,
0
1
2
These are the most simple way to get repeatative output.
Use when you want the code to run at least once before checking the condition.
Let's take the same "Hello" example using do...while
:
let i = 1;
do {
console.log("Hello");
i++;
} while(i <= 5);
✅ Use when you know how many times to repeat.
for(let i = 1; i <= 10; i++) {
console.log("Ticket #" + i);
}
🔁 Use when you don’t know how many times to repeat, but have a condition to stop.
let guess;
while(guess !== 5) {
guess = prompt("Guess the number:");
}
👌 Use when you want to run code at least once before checking the condition.
let choice;
do {
choice = prompt("1. Start\n2. Help\n3. Exit");
} while(choice !== "3");