while
Loopwhile
statementwhile
loopwhile
Loopwhile
Loop with ArrayThe JavaScript while loop is also known as an entry control loop. The JavaScript while
is test specified condition before executing a block of code. If the condition met true, then the block of code will be executed.
while
Loopwhile (expression) {
// statement
}
The while
loop test specified the condition
before execute the block of code.
If the condition
specified condtion met true
, the while
loop executes the block of code
. If the specified condition met false
, execution will be stopped.
You have known above, the while
loop is known as an entry control loop. For this reason, it is possible that the block of code
inside the while
loop is never executed, if the specified condition met false.
while
loopIn the case, if the specified condition is found to be false. And still, you want to execute a block of code at least once. So you should use the do while Loop.
while
loopSee the following example that uses the while
loop in javascript:
<script>
let count = 1;
while (count < 10) {
document.write(count + "<br>");
count +=2;
}
</script>
How the script works:
count
variable and assign value to it.while
loop checks specified condition, if count
is less than 10
and execute the statements inside the loop body.count
by 2
. And After 5
iterations, the condition count < 10
met false and loop will be terminate.The output of the script shown below:
1
3
5
7
9
while
Loop with ArrayThe following example uses the while
loop to generate 5 random numbers and push into an array.
<script>
// create an array empty array
let rands = [];
// define a count variable and assign value zero to it
let count = 0;
// define a size variable and assign value 5 to it
const size = 5;
//test condition
while(count < size) {
rands.push(Math.round(Math.random() * 10));
count++;
console.log('The current size of the array is ' + count);
}
console.log(rands);
Output:
The current size of the array is 1
The current size of the array is 2
The current size of the array is 3
The current size of the array is 4
The current size of the array is 5
[1, 9, 1, 9, 6]
In this example:
count and size
variable and assign value to it.while
loop terminated. When the the count
equals the value of the size
variable.In this tutorial, you have learned how to use the JavaScript while
loop with executed a block of code until the specified condition is met true
.
☞ JavaScript Programming Tutorial Full Course for Beginners
☞ Learn JavaScript - Become a Zero to Hero
☞ Javascript Project Tutorial: Budget App
☞ JavaScript for React Developers | Mosh
☞ E-Commerce JavaScript Tutorial - Shopping Cart from Scratch