JavaScript While Loop with an Example

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.


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,

JS while Loop Flow Chart
JS while Loop Flow Chart

Example of JavaScript While Loop



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 .


“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 (

Also Read:

Happy Coding..!

Was this article helpful?
My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH. I am a web Programmer by profession and working on more than 50 projects to date. Currently I am working on the web-based project and all the CMS and frameworks which are based on PHP.
Posts created 189

One thought on “JavaScript While Loop with an Example

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top