JavaScript Making Decisions

The IF statement

The most common way that a comparison is used is directly within an if statement. Here is an example.

if (mark >= pass) {
    subjectsPassed += 1;

As you can see, an if statement starts with the reserved word if. This is followed by the Boolean value to be tested contained within parentheses. We have put an expression there that gets evaluated to a Boolean value in this example. If we already had a Boolean variable that contained the value that we wanted to test then we could just place that variable by itself inside of the parentheses.

The braces { and } are optional but are best included. One of the things that braces do in JavaScript is to group one or more statements together into a block of content. That content can then be put anywhere in the code where a single statement is allowed to go. If we leave the braces out from the if statement, then only the statement immediately following the condition is included in the if test. Were the condition to return false then that single statement would be skipped and the statement after that would be the next one to be run. With the braces there all of the statements within the braces are part of the if statement and where returns false the next statement after the closing brace is the next one to run.

Our example if statement only contains one statement and the braces are therefore optional. It is still best to put them in as this makes it easier to include a second statement inside the if when required (for example, temporary code added during testing that will tell us whether the if statement runs that code or not).

go to previous section go to next section 


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow