Almost all JavaScript code eventually comes to a decision, a judgement whether or not to take an action. This is usually resolved with an if
statement:
if (condition) { statement(s); }
The condition may be an expression using any valid combination of operators. If the expression evaluates as true, the statement(s) in the curly braces are executed.
For new coders it’s particularly important to check that an if
condition will resolve to true
or false
:
if (4 > 5) { console.log("Impossible!"); }
In the statement above, “Impossible!” will never be written to the console, as 4 can never be greater than 5. Similarly:
if (4 > 3) { console.log("Noduh"); }
The above statement will always be executed, and should not be in an if
.
The Path Not Taken
To take care of alternatives, you can place statements in a else
:
if (condition1) {
statement1
} else {
statement2
}
If the condition is met, statement1
is executed; if the condition evaluates to false
, statement2
will be executed instead.
More Accurate Elses
if else
is a “either this or this” decision. We can clarify our forked conditions further by using an else if
construction. For example:
if (condition1) {
statement1
} else if (condition2) {
statement2
} else if (condition3) {
statement3
} else {
general statement
}
more code…
In the above code, condition1
will be tested first. If it evaluates to true
, statement1
will be executed, and the code will move on more code
. If it is not met, condition2
will be tested, followed by condition3. If either of those evaluate as true
, their respective statements will be run exclusively, and execution will move on to more code
. If both of them test as false
and condition1
is false
, the general statement
will be run.
Nested Decisions
It is also possible to nest if
statements:
if (condition1) {
statementA;
} else {
if (condition2) {
statementB;
} else {
statementC;
}
}
Functionally, nested if
statements can have the same result as else if
statements: your choice to use one or the other is largely a matter of taste, convenience and coding style.
Conclusion
There are more ways to create branching decisions in JavaScript than if - else
statements, including switch
, which we will be looking at next.
Photograph by Brandon Oh, licensed under Creative Commons
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.