JavaScript offers different types of looping statements to execute a block of code repeatedly based on certain conditions. These are used to execute a block of code repeatedly based on certain conditions.
There are different types of looping statements in JavaScript, including:
Looping statement in JavaScript with example
Simple example code.
for
loop:
The for
loop is used to execute a block of code a fixed number of times.
for (let i = 0; i < 5; i++) {
console.log(i);
}
while
loop:
The while
loop is used to execute a block of code as long as a condition is true.
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
do-while
loop:
The do-while
loop is used to execute a block of code at least once, and then repeated as long as a condition is true.
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
for...in
loop:
The for...in
loop is used to iterate over the properties of an object.
<!DOCTYPE html>
<html>
<body>
<script>
const person = {
name: 'John',
age: 30,
gender: 'male'
};
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
</script>
</body>
</html>
Output:
for...of
loop:
The for...of
loop is used to iterate over the values of an iterable object (e.g., an array).
const arr = ['apple', 'banana', 'cherry'];
for (const item of arr) {
console.log(item);
}
Each loop has a different use case and syntax, and this article provides examples for each type to demonstrate how to use them in practice.
Do comment if you have any doubts or suggestions on this Js basic topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version