In this lesson we will talk about the JavaScript while loop and we will also do some very simple examples to understand how it works.

The while is a pre-conditional construct, that is, the condition check occurs before the execution of the instructions indicated in curly brackets.

The syntax of the while loop is as follows:

while (condition) {
   istructions;
}

Where condition represents a Boolean value, that is, a true or false value. The condition determines the length of the cycle that will then run as long as the condition is true.

So as long as the condition is true, the instructions indicated in braces will be executed.

So be careful to set the condition correctly.

Banner Pubblicitario

The cycle will be infinite if the condition is always true.

While the cycle will never run if the condition is false from the start.

JavaScript while loop – first exercise

Display the numbers 0 to 9 in ascending order.

First we initialize a counter variable to 0 to start from: c = 0.

Then we set the condition in the while, in this case c <10.

Then inside the curly brackets we insert our instructions: we write the variable c and then we increment it by 1.

You will then have these steps:

Banner pubblicitario

c = 0

step 1:

the condition: 0 <10 is true:

print 0

increases c by 1: c = 1

step 2:

the condition: 1 <10 is true:

print 1

increases c by 1: c = 2

it is so on until c = 9

So here is the complete code of the while loop in JavaScript.


var c = 0;
while (c < 10){
   document.write(c + '');
   c++;
}

JavaScript while loop - second exercise

Display even numbers from 0 to 100.

To carry out this simple exercise, just change the previous algorithm by increasing c by 2 instead of 1.

We change the condition to also include 100: c <= 100.

We also remember that 0 is an even number.

Here is the complete code:



var c = 0;
while (c <= 100){
   document.write(c + '');
   c += 2;
}

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript variables and costants