JavaScript while Loop or any other loops are used to execute a block of code till the condition is true.
Introduction to the JavaScript while loop statement
JavaScript while
statement creates a loop that executes the block of code till satisfies the given conditions or condition going to be true.
Syntax:
1 2 3 |
while (expression) { // statement } |
In the above syntax while
statement checks the expression
or given condition before each iteration of the loop.
Sometimes the code which is inside the while loop did not execute, because the while loop statement checks the condition or expression first. If the condition is not satisfied then the loop will be terminated.
Here is the JS while loop flow chart image for better understanding,
Example of JavaScript While Loop
1 2 3 4 5 |
let count = 0; while (count < 10) { console.log(count); count +=2; } |
Output:
0
2
4
6
8
How The JS While Loop Works on Above Code:
- First, we set the variable
count
zero outside the loop. - Second, before the first iteration, the while loop checks the count’s value is less than 10 or not.
- At last, it prints the count’s value on the console and iterates the loop till the count is less than 10.
Example of JS While Loop with an Array
In this example we push numbers between 1 to 10 to an array .
1 2 3 4 5 6 7 8 9 10 11 12 |
// create an array of five random number between 1 and 10 let rands = []; let count = 0; const size = 5; 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”
[3, 5, 8, 3, 9]
Explanations of above code:
- First, we initialize an empty array to push the generated numbers.
- Second, add the random number between 1 to 10 then iterate the loop till the count value equals the size.
Here is the complete explanation of the JavaScript While Loop with the complete running example.
Please let know if facing any issue. To know more go here Statements and declarations – JavaScript | MDN (mozilla.org)
Also Read:
- How to Get Current Date and Time In JavaScript
- Set PHP Error Reporting Into The PHP File
- How to Convert JSON to Array PHP
- Remove Duplicates From an Array in JavaScript Without Using For Loop
Happy Coding..!
One Reply to “JavaScript While Loop with an Example”