How To

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...

Written by Bikash · 1 min read >
JS while Loop Flow Chart

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:

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

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 .

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:

Happy Coding..!

Was this article helpful?
YesNo
Written by Bikash
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. Profile

One Reply to “JavaScript While Loop with an Example”

Leave a Reply

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