Loops in JavaScript
Loops are a fundamental concept in programming used to execute a block of code repeatedly based on a condition. JavaScript offers several types of loops such as for, while, and do-while, each serving different purposes depending on the situation.
Types of Loops in JavaScript:
- for loop: A traditional loop that repeats a block of code a set number of times.
- while loop: A loop that repeats as long as a specified condition is true.
- do-while loop: A loop that executes at least once before checking the condition.
- for...in loop: Used to iterate over properties of an object.
- for...of loop: Used to iterate over iterable objects like arrays, strings, etc.
Syntax of Loops:
for loop Syntax
for (let i = 0; i < 5; i++) {
console.log(i);
}
Example of for loop in JavaScript:
This example uses a for
loop to print numbers from 0 to 4.
Example
for (let i = 0; i < 5; i++) {
console.log(i);
}
Output
0
1
2
3
4
1
2
3
4
while loop Syntax
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Example of while loop in JavaScript:
This example uses a while
loop to print numbers from 0 to 4.
Example
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Output
0
1
2
3
4
1
2
3
4
do-while loop Syntax
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Example of do-while loop in JavaScript:
This example uses a do-while
loop to print numbers from 0 to 4. The loop will run at least once even if the condition is initially false.
Example
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Output
0
1
2
3
4
1
2
3
4
Key Points on Loops:
- for loop: It is typically used when the number of iterations is known beforehand.
- while loop: It is ideal when the number of iterations is not known, and the loop continues as long as the condition is true.
- do-while loop: Useful when you want the code to execute at least once, regardless of the condition.
- Break: The
break
statement can be used to exit the loop before it has finished all iterations. - Continue: The
continue
statement can be used to skip the current iteration and move to the next iteration of the loop.