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

8,812 visits, 21,477 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

This is part 4 of the tutorial series Learn JavaScript in Construct. This part continues on from part 3. So in case you missed it, see Learn JavaScript in Construct, part 3: Operators.

In this part we'll start off by using the same project as before. Later we'll introduce a new project to try out what we've learnt.

'If' statements

It's common in programming that you want to do some things only if certain conditions are met - for example if the password is correct, then allow the login. This is what the if statement does.

In JavaScript the 'if' statement takes the following form:

if (condition)
{
	// Statements to run if condition is true
}

// The following statements always run

Notice that the statements in between the { and } following the if statement are only run if condition is true (or truthy). It's useful to use the various comparison operators we covered in the previous part for the condition, such as number < 10. Try the following code snippet in your Construct project and look in the browser console to see the result.

let number = 5;
if (number < 10)
{
	console.log("Number is less than 10!");
}

console.log("Logged after if statement");

This will log both Number is less than 10! and then Logged after if statement. Since number < 10 is true, the code inside the 'if' statement runs, and then the code afterwards always runs.

Now try changing number to initialise to 15. The condition number < 10 is now false, so the code inside the 'if' statement does not run. Therefore the only message logged is Logged after if statement, since that comes after the 'if' statement.

Similar to the ?: conditional operator, the 'if' statement condition can be any value and it will be interpreted as either truthy or falsy. For example you could use just if (number), and this will count as false if number is zero or NaN, otherwise true.

Else

'If' statements can also be immediately followed by an 'else' statement. The code inside the 'else' statement runs if the condition is false (or falsy). Try the following code snippet.

let number = 15;
if (number < 10)
{
	console.log("Number is less than 10!");
}
else
{
	console.log("Number is greater or equal to 10!");
}

Since number is initialised to 15, the condition number < 10 is false, and so the code in the 'else' statement runs, logging: Number is greater or equal to 10!

When there is both an 'if' and an 'else' statement, one of the two sections is guaranteed to run, as they correspond to the two possible outcomes of the condition.

Else if

Multiple conditions can be chained using the else if pattern like so.

let number = 15;
if (number < 10)
{
	console.log("Number is less than 10!");
}
else if (number < 20)
{
	console.log("Number is between 10 and 20!");
}
else
{
	console.log("Number is greater or equal to 20!");
}

Try changing the initial value of number to get each message to appear.

Optional braces

You can put as many statements as you like in between the { and } braces, including further 'if' statements. However if there is only a single statement in between the braces, the braces can be omitted. For example this:

if (number < 10)
{
	console.log("Number is less than 10!");
}

is equivalent to this:

if (number < 10)
	console.log("Number is less than 10!");

as there is only a single statement. This also applies to 'else' and 'else if' chains, so for example this:

let number = 15;
if (number < 10)
{
	console.log("Number is less than 10!");
}
else if (number < 20)
{
	console.log("Number is between 10 and 20!");
}
else
{
	console.log("Number is greater or equal to 20!");
}

is equivalent to this:

let number = 15;
if (number < 10)
	console.log("Number is less than 10!");
else if (number < 20)
	console.log("Number is between 10 and 20!");
else
	console.log("Number is greater or equal to 20!");

Whitespace

In general, JavaScript doesn't care about whitespace (i.e. spaces and tabs). This allows a lot of flexibility in how code is laid out. The following code snippet shows several ways to write an 'if' statement, all of which are equivalent.

if (number < 10)
{
	console.log("Number is less than 10!");
}

if (number < 10) {
	console.log("Number is less than 10!");
}

if (number < 10)
	console.log("Number is less than 10!");

if(number<10)console.log("Number is less than 10!");

if (number < 10) { console.log("Number is less than 10!"); }

if    (number    <    10)
{
console.log("Number is less than 10!");
}

In practice it's best to stick to a sensible style (avoiding the extremes of adding lots of spaces or removing as many spaces as possible), and just be consistent about using the same style. This guide will stick to the first form above.

Prefer braces

While omitting the braces is sometimes a useful shorthand, it's generally preferable to include them. This helps keep the code clear and readable and avoid mistakes.

One common mistake omitting braces comes from the fact JavaScript ignores indentation - it's only there for readability. Therefore if you write code like this:

if (number < 10)
	console.log("First message!");
	console.log("Second message!");

This might look like both messages are logged if number < 10, but it is actually equivalent to this:

if (number < 10)
{
	console.log("First message!");
}

console.log("Second message!");

This is because when the braces are omitted, only the single following statement counts as inside, regardless of indent. Preferring to use braces helps avoid this potential mistake.

Prefer 'if' statements to ?:

It's sometimes possible to use either an 'if' statement or the conditional ?: operator. For example the following 'if' statement:

let number = 5;
let message;
if (number < 5)
{
	message = "Number is less than 5!";
}
else
{
	message = "Number is greater or equal to 5!";
}
console.log(message);

is equivalent to this:

let number = 5;
let message = number < 5 ? "Number is less than 5!" : "Number is greater or equal to 5!";
console.log(message);

Despite the latter being fewer lines of code, the former is generally regarded as more readable. So if in doubt prefer to use 'if' statements. The conditional operator has its uses, but is best when all three parts are very short and simple.

  • 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!