Introduction to JavaScript : Loops

Loops

A loop executes a set of instructions (code block) repeatedly as long as a specified condition is met. JavaScript like many other programming languages offer several ways of repeating a block of code.

While loop

In a while loop, the condition is always evaluated before the block of code is executed.

let x = 10
const sum = 50
while (x < sum) {
   console.log(x)
   x += 10
}

In the example above, the condition x < sum is checked on every iteration until x is greater that or equal to the defined sum (50).

Output:

10

20

30

40

do...while loop

A do...while loop is like a while loop except that the block of code is executed at least once. 

let x = 10
const sum = 50
do {
   console.log(x)
   x += 10
}
while (x < sum) 

The output of the example above is exactly equal to the output of the while loop except that the block of code in the do..while loop is executed for the first time before the condition is checked.

For loop

The for loop is the most common loop in many programming languages. It consists of an initialization which initialises the variable(s) for the loop, a condition, which must be met before the code block is executed and finally and afterthought or an update by which the test variable is updated (i.e incremented).

const sum = 5
for (let x = 0; x < sum; x++) {
   console.log(x)
}

Output:

0

1

2

3

4

The loop terminates when the value of x becomes greater or equal to sum (5). 


course logo
Introduction to JavaScript
Number of sections:
10
Content length:
Delivery formats: