JavaScript While Loop
JavaScript While Loop is used to execute a block of code for a number of times based on a condition.
In this tutorial, we will learn how to define/write a JavaScript While loop, and its usage using example programs.
Syntax
The syntax of JavaScript While Loop is
</>
Copy
while (condition) {
//statements
}
where condition is the expression which is checked before executing the statements inside while loop.
Examples
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>
We can also use a while to iterate over the elements of an array, using array length in condition, as shown in the following example.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var arr = [10, 20, 30, 40];
var i = 0;
while (i < arr.length) {
document.getElementById('output').innerHTML += arr[i] + '\n';
i++;
}
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned about While Loop, its syntax, and usage with examples.