Explain JavaScript Loops
JavaScript loops are used to repeat a block of code multiple times. Here are the main types of loops in JavaScript:
Types of JavaScript Loops
1. for Loop
The for loop repeats a block of code as long as a specified condition is true.
Syntax
for (initialization; condition; increment) {
// code block to be executed
}
Example
for (let i = 0; i < 5; i++) {
console.log(i);
}
Output
0
1
2
3
4
2. while Loop
The while loop repeats a block of code as long as a specified condition is true.
Syntax
while (condition) {
// code block to be executed
}
Example
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Output
0
1
2
3
4
3. do...while Loop
The do...while loop is similar to the while loop, but it executes the block of code once before checking the condition.
Syntax
do {
// code block to be executed
} while (condition);
Example
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Output
0
1
2
3
4
4. for...in Loop
The for...in loop is used to iterate over the properties of an object.
Syntax
for (variable in object) {
// code block to be executed
}
Example
const person = {fname: "John", lname: "Doe", age: 25};
for (let key in person) {
console.log(key + ": " + person[key]);
}
Output
fname: John
lname: Doe
age: 25
5. for...of Loop
The for...of loop is used to iterate over the values of an iterable (like an array or a string).
Syntax
for (variable of iterable) {
// code block to be executed
}
Example
const arr = [10, 20, 30, 40, 50];
for (let value of arr) {
console.log(value);
}
Output
10
20
30
40
50
Example of Using Loops Together
Here's an example of using different loops to achieve the same result, printing numbers from 1 to 5:
Using for Loop
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Using while Loop
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
Using do...while Loop
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
Summary
When to Use Each Loop
forLoop – Best when you know the number of iterations in advance.whileLoop – Best when the number of iterations depends on a condition.do...whileLoop – Best when the code must execute at least once before checking the condition.for...inLoop – Used to iterate over the properties of an object.for...ofLoop – Used to iterate over the values of iterable objects such as arrays and strings.
These are the basic loops in JavaScript and how they can be used to execute a block of code multiple times. Each loop type serves a different purpose and can be chosen based on the specific needs of the task.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
