Learn JavaScript in Construct, part 4: control flow

24

Index

Features on these Courses

Attached Files

The following files have been attached to this tutorial:

.c3p

guess-the-number-js.c3p

Download now 49.84 KB
.c3p

Stats

9,221 visits, 22,240 views

Tools

Translations

This tutorial hasn't been translated.

License

This tutorial is licensed under CC BY-NC 4.0. Please refer to the license text if you wish to reuse, share or remix the content contained within this tutorial.

Published on 11 Oct, 2021. Last updated 16 Dec, 2021

While loops

Another important part of programming are loops. These are bits of code that can be repeated over and over again. We'll cover two kinds of loops in this guide: while loops and for loops. (There are some other types of loops JavaScript, but these are two of the fundamental kinds of loops.)

At first glance while loops have a similar structure to an 'if' statement: a condition with a series of statements in braces.

while (condition)
{
	// statements to repeat
}

However unlike an 'if' statement, it can repeat the statements inside it. It works as follows:

  1. Check to see if condition is true (or truthy).
  2. If it's true, run the statements, and go back to step 1.
  3. If it's false, don't run the statements. It will continue to the next statement after the loop.

In other words, it repeats the statements in the loop while the condition is true - hence the name while loop.

Let's go back to the project we were using previously with a JavaScript code block in an On start of layout event to try it out. Use the following code:

let i = 0;
while (i < 3)
{
	console.log(`Variable 'i' is ${i}`);
	i++;
}

Here's a project file with this already entered to make it easy to get back to this setup.

.C3P

while-loop.c3p

Download now 46.86 KB

Preview the project and check the browser console. It should log three messages:

Variable 'i' is 0
Variable 'i' is 1
Variable 'i' is 2

Note we made use of a template string with the backtick characters `, using ${i} to insert the value of i in to the string.

How does this work? The statements inside the loop - also known as the loop body - log the value of i to the browser console, then increment i (i.e. adds 1 to it). The value of i starts off as 0, so this will repeat the loop body three times:

  1. First i is 0, so i < 3 is true. The loop body runs, printing the value of i and incrementing it to 1.
  2. Then i is 1, so i < 3 is true, and the loop body runs again.
  3. Then i is 2, so i < 3 is true, and the loop body runs again.
  4. Then i is 3, and i < 3 is now false. The loop ends.

The end result is a loop that repeats some code three times.

For loops

It turns out that the pattern we just used, using a variable to count up and repeat some code a certain number of times, is very common in programming. Therefore most programming languages, including JavaScript, provide a more concise way to write that.

In general terms the pattern is the following:

begin
while (condition)
{
	// loop body

	step
}

The for loop combines all of these in to one statement in the form:

for (begin; condition; step)
{
	// loop body
}

So the following 'for' loop is identical to the 'while' loop we used previously, just using a shorter form:

for (let i = 0; i < 3; i++)
{
	console.log(`Variable 'i' is ${i}`);
}

This provides a concise way to repeat some code a certain number of times - try changing the 3 in the condition to a different number, and you'll see it log the message the corresponding number of times.

Each of the three parts of the 'for' loop are optional. For example the 'begin' part can be omitted, e.g. if the variable is already declared.

let i = 0;
for ( ; i < 3; i++)	// note first part left empty
{
	console.log(`Variable 'i' is ${i}`);
}

An empty condition also counts as true - so the loop will run forever! This will come up again shortly.

Break

The break statement can be used to end a loop early. Try the following loop - it's set to run 10 times, but the break will stop it when i reaches 5.

for (let i = 0; i < 10; i++)
{
	console.log(`Variable 'i' is ${i}`);

	if (i === 5)
		break;	// end loop early
}

This will log up to Variable 'i' is 5, and then end the loop early when it runs the break statement. You can use break in both 'for' and 'while' loops.

Infinite loops

It's possible to set up a loop with a condition that is always true, so it's set to repeat the loop body forever. This can be done with while (true) or for (;;) (where all three parts of the 'for' loop are left empty: no variable declared, no condition, and no step).

Then the only way to end the loop is with the break statement. This must be run at some point, otherwise the loop will never end. This is one possible cause of software 'hanging', i.e. freezing and stopping responding - it's stuck in an endless loop and never gets the chance to respond to further inputs.

Here's an example of a supposedly infinite loop that uses break to end it.

let i = 0;
while (true)
{
	console.log(`Variable 'i' is ${i}`);
	i++;

	if (i === 5)
		break;	// end infinite loop
}

This is equivalent to using a 'for' loop to repeat a certain number of times. However this approach of writing an infinite loop that's ended with break can be useful in more complex situations where you don't actually know in advance how many iterations need to be run, so it's useful to be aware of the approach.

Continue

The continue statement ends the loop body early, but continues running the loop. Each run of the loop is called an iteration, so another way of putting this is it cancels the current iteration and skips to the next iteration. Try the following code sample.

for (let i = 0; i < 10; i++)
{
	if (i === 5)
		continue;	// skip logging message

	console.log(`Variable 'i' is ${i}`);
}

This logs every value of i from 0 to 9, but skips 5. This is because when i is 5, it runs the continue statement, which skips ahead to the next iteration where i is 6. You can use continue in both 'for' and 'while' loops.

  • 4 Comments

  • Order by
Want to leave a comment? Login or Register an account!
  • Why do we need to use the tilde mark in the console.log (`Variable `i`is ${i}`); I was getting errors because i thought they were single quotations.

  • As aulas estão sendo maravilhosas. Muito obrigado pela disponibilidade e paciência!!

  • Thanks for the lessons!