Last Updated : 26 Dec, 2024
Loops in JavaScript are used to reduce repetitive tasks by repeatedly executing a block of code as long as a specified condition is true. This makes code more concise and efficient.
Suppose we want to print 'Hello World' five times. Instead of manually writing the print statement repeatedly, we can use a loop to automate the task and execute it based on the given condition.
JavaScript
for (let i = 0; i < 5; i++) {
console.log("Hello World!");
}
Hello World! Hello World! Hello World! Hello World! Hello World!
Let's now discuss the different types of loops available in JavaScript
1. JavaScript for LoopThe for loop repeats a block of code a specific number of times. It contains initialization, condition, and increment/decrement in one line.
Syntax
for (initialization; condition; increment/decrement) { // Code to execute }JavaScript
for (let i = 1; i <= 3; i++) {
console.log("Count:", i);
}
Count: 1 Count: 2 Count: 3
In this example
The while loop executes as long as the condition is true. It can be thought of as a repeating if statement.
Syntax
while (condition) {JavaScript
// Code to execute
}
let i = 0;
while (i < 3) {
console.log("Number:", i);
i++;
}
Number: 0 Number: 1 Number: 2
In this example
The do-while loop is similar to while loop except it executes the code block at least once before checking the condition.
Syntax
do {JavaScript
// Code to execute
} while (condition);
let i = 0;
do {
console.log("Iteration:", i);
i++;
} while (i < 3);
Iteration: 0 Iteration: 1 Iteration: 2
In this example:
The for...in loop is used to iterate over the properties of an object. It only iterate over keys of an object which have their enumerable property set to “true”.
Syntax
for (let key in object) {JavaScript
// Code to execute
}
const obj = { name: "Ashish", age: 25 };
for (let key in obj) {
console.log(key, ":", obj[key]);
}
name : Ashish age : 25
In this example:
The for...of loop is used to iterate over iterable objects like arrays, strings, or sets. It directly iterate the value and has more concise syntax than for loop.
Syntax
for (let value of iterable) {JavaScript
// Code to execute
}
let a = [1, 2, 3, 4, 5];
for (let val of a) {
console.log(val);
}
Choosing the Right Loop
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4