Loops (JavaScript)

Loops

> Tutorial

We are now going to look at another kind of structure that is just as fundamental as conditions: loops!

A loop lets you repeat instructions several times. There are several kinds, bounded and unbounded, which we'll cover in this section.

while loop

The unbounded while loop has a syntax similar to the if we saw earlier. It runs a block of instructions as long as a condition is met.

Here is an example:

When run, this code displays the following in the logs: > Counter is 1 Counter is 2 Counter is 3 Counter is 4 Counter is 5

do while loop

The unbounded do while loop is similar to the while loop, except that the condition comes at the end, so the body of the loop is always run at least once:

for loop

The for loop is a bounded loop that looks like a while loop, but more compact.

The for loop has three parts:

Example of a for loop:

Attacking several times in a row

Our leek has between 10 and 13 TP (thanks to Motivation) and the Pistol only costs 3 TP, so we can use it 4 times at most.

We use a for loop to call the me.useWeapon() method 4 times in a row:

Here our variable i takes the values 0, 1, 2 and 3, so the loop runs 4 iterations.

❓ Quiz

What is a loop used for?

Running instructions several times Making your code more compact Speeding up part of your code Running instructions in parallel

Which code(s) are correct?

let x = 0 while (x < 10) { x += 2 } let x = 0 for (let i = 0; i < 10) { x += 2 } let x = 0 while { x += 2 } do (x < 10) let x = 0 for (; x < 10;) { x += 2 }

Full AI