JavaScript Loop Statements
Loop statements are used to execute a block of code repeatedly for a number of times, or execute a block of code for each item in an iterable, etc.
Looping Statements
The following tutorials cover the looping statements in detail with examples.
Control Statements
The following tutorials cover the loop control statements.
Examples
We will go through examples for each of these statements.
For Loop
For loop is used to execute a block of code repeatedly for a number of times based on a condition.
In the following example, we use for loop to display ‘hello world’ ten times in a pre HTML block.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
for (let i = 0; i < 10; i++) {
document.getElementById('output').innerHTML += 'hello world\n';
}
</script>
</body>
</html>
For-in Loop
For-in loop is used to execute a block of code for each property of the given object.
In the following example, we take an object where the objects consists of some properties (key:value pairs), and iterate over these properties using For-in loop.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var obj = {name: 'Apple', age: '22', location: 'California'};
for (key in obj) {
let value = obj[key];
document.getElementById('output').innerHTML += key + '\t:\t' + value + '\n';
}
</script>
</body>
</html>
For-of Loop
For-of loop is used to execute a block of code for each element of an iterable object.
In the following example, we take an array, which is an iterable object, and use For-of loop to iterate over the items of this array.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var obj = ['apple', 'banana', 'orange'];
for (item of obj) {
document.getElementById('output').innerHTML += item + '\n';
}
</script>
</body>
</html>
While Loop
While loop is used to execute a block of code a number of times in a loop, based on a condition.
In the following example, we execute a block of code that appends ‘hello world’ to a pre block HTML element ten times using a While Loop.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var i = 0;
while (i < 10) {
document.getElementById('output').innerHTML += 'hello world\n';
i++;
}
</script>
</body>
</html>
Do-While Loop
Do-While loop is used to execute a block of code for one or more number of times in a loop, based on a condition.
In the following example, we execute a block of code that appends ‘hello world’ to a pre block HTML element ten times using a Do-While Loop.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var i = 0;
do {
document.getElementById('output').innerHTML += 'hello world\n';
i++;
} while (i < 10);
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned about different Loop statements in JavaScript, their syntax, and usage with examples.