JavaScript Loops
JavaScript loops, such as for, while, do-while, and for-in, are used to
iterate over code, making it more concise. They are commonly used with arrays.
JavaScript has four types of loops.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
JavaScript for loop
The JavaScript `for` loop iterates over elements a fixed number of times. It
is best used when the number of iterations is known. The syntax for the `for`
loop is shown below.
Statement:
for (initialization; condition; increment/decrement) {
// code block to be executed
}
Example
Here's a simple example of a `for` loop in JavaScript.
<Script>
for (let i = 0; i < 5; i++) {
console.log("Hello, World!");
}
</Script>
output:
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
JavaScript while loop
The JavaScript `while` loop can iterate indefinitely. It is best used when the
number of iterations is unknown. The syntax for the `while` loop is shown
below.
Statment :
while (condition) {
// code block to be executed
}
Example
Here’s a simple example of a while loop in JavaScript.
<Script>
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
</Script>
output:
0
1
2
3
4
JavaScript do while loop
The JavaScript do-while loop, like the while loop, can iterate indefinitely.
However, unlike the while loop, the code inside a do-while loop is executed at
least once, regardless of whether the condition is true or false. The syntax
of the do-while loop is shown below.
Statement:
do {
// code block to be executed
} while (condition);
Example
<Script>
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
</Script>
output:
0
1
2
3
4
JavaScript for in loop
The JavaScript for-in loop is used to iterate over the properties of an
object.
Statement:
for (variable in object) {
// code block to be executed
}
Example:
let person = {name: 'John', age: 30, city: 'New York'};
for (let prop in person) {
console.log(prop + ': ' + person[prop]);
}
output:
name: John
age: 30
city: New York