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.

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
My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH, my native place in Odisha. I am a Web Programmer by profession and working on more than 50 projects to date. My passion is working on the web-based project using PHP and relate to all CMS and frameworks which is based on PHP.
Posts created 175

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
mariobet - supertotobet - escort -

takip7.com

- milanobet giriş - gizabet giriş -
perabet giriş
- betkanyon giriş -

jojobet giriş

We are now accepting guest posting and creation of back-links.
This is default text for notification bar