Dev
JavaScript Loops: why we use them - the first 3 types
Dev.toUnited States · NORTH AMERICA
while learning javascript I came across loops but before learning different types of loops, I want understand one question - why do we use loops? Why do we use loops? Loops allow us to repeat a block...
while learning javascript I came across loops
but before learning different types of loops, I want understand one question - why do we use loops?
Why do we use loops?
Loops allow us to repeat a block of code without rewrite same code again and again.
For example , without loop:
console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);
with loop:
for(let i=1;i<=5;i++){
console.log(i);
}
The loop becomes especially useful when working with large amounts of data, such as arrays.
Types of loop:
1.for loop:
A for loop is useful when you know how many times you want to repeat something.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
2.while loop:
A while loop checks the condition before executing the code.
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
If the condition is false from the beginning, the loop won't execute.
3. do...while Loop
A do...while loop executes the code first and checks the condition afterward.
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
This means it will execute at least once.
Quick way to remember
for - repeat with initialization, condition & update
while - check → execute
do...while - execute → check
The key difference:
while can execute zero times, but do...while executes at least once.