This content originally appeared on DEV Community and was authored by Vidya
What is a Loop?
A loop is used to repeat a block of code until a certain condition is met. It saves time and makes your program shorter and cleaner.
For Loop:
The for loop runs a block of code a specific number of times.
Syntax:
for(initialization; condition; increment){
// code to be executed
}
Example:
for (let i=1; i<=5; i++) {
console.log("Number: " + i);
}
output --> Number:1
Number:2
Number:3
Number:4
Number:5
While Loop:
The while loop runs code as long as the condition is true.
Syntax:
While (condition) {
// code to be executed
}
Example:
let i=1;
while (i <= 3) {
console.log("Hello" + i);
i++;
}
output --> Hello 1
Hello 2
Hello 3
Do….While Loop:
The do..while loop runs at least once, even if the condition is false.
Syntax:
do{
// code to be executed
} while (condition);
Example:
let i=1;
do{
console.log("Count: " + i);
i++;
} while (i <= 3);
output ---> Count:1
Count:2
Count:3
This content originally appeared on DEV Community and was authored by Vidya