Introduction
When writing a program, you rarely want the exact same outcome every time. Often you will receive some data, inspect the data and decide how to proceed based on that data. For example, in a web application you may like to apply different classes to odd and even table-rows to create visual distinctions. In a game you would want to take different actions if a player hits an obstacle than if they didn’t. We can fork programs into different operational paths using if
statements.
The use of if
statements relies on boolean data types, switching paths depending on whether a condition is true
or false
.
The syntax
In javascript an if
statement looks something like this:
firstStatements;
if (condition) {
conditionalStatements;
}
lastStatements;
In this example, should the condition
resolve to true
the program would execute firstStatements
, conditionalStatements
, then lastStatements
. However should condition resolve to false
the program would only execute firstStatements
and lastStatements
, skipping over the conditional statements without executing them.
Occasionally, you may like to take an alternative action, should the condition be false. In which case your code will look like this:
firstStatements;
if (condition) {
conditionalStatements;
} else {
alternativeStatements;
}
lastStatements;
In this example, should the condition
evaluate to true the program would still execute firstStatements
, conditionalStatements
, then lastStatements
as before. However, this time when the statement is false it will execute firstStatements
, alternativeStatements
, then lastStatements
. As before, the first & last statements are always executed, as they are outside of the flow.
Sometimes, you may also need to chain multiple conditionals. For this we have else if
used like this:
firstStatements;
if (condition) {
conditionalStatements;
} else if (secondCondition) {
differentStatements;
} else {
alternativeStatements;
}
lastStatements;
In this example, the differentStatements
will only be run if the first condition fails, and the second condition passes. The alternativeStatements
will only run if both conditions fail.
some real-world examples
Example 1
var str = document.getElementById('nameField').value;
if (str.length > 20) {
str = str.substr(0, 18) + '...';
}
In example 1, we fetch a string value from an input field. We then compare the length of the string to a desired maximum display length (20) and if it exceeds that length, we cut it down to it’s first 18 characters, and append an ellipsis.
Example 2
function addDelivery(basket) {
if (basket.getTotal() < 100) {
basket.addItem('delivery', 10.00);
}
}
In this example, we add a delivery charge of £10.00 to someones shopping bill, only if the basket contains items totalling less than £100.
Example 3
function fixHeader(el, elOffsetTop, scrollY) {
if (scrollY >= elOffsetTop && !el.classList.contains('fixed')) {
el.classList.add('fixed');
} else if (scrollY < elOffsetTop && el.classList.contains('fixed')) {
el.classList.remove('fixed');
}
}
In this example, a DOM element (el
) has a class of fixed
added or removed depending on the scroll position of the document.
Example 5
function fizzBuzzNumber(n) {
var str = '';
if (n % 3 === 0) {
str += 'Fizz';
}
if (n % 5 === 0) {
str += 'Buzz';
}
if (str.length > 0) {
return str;
} else {
return '' + n;
}
}
In this function, the popular coding challenge FizzBuzz
is solved using if / else statements. An integer Number
is supplied and checked to see if it divides by 3 or 5. If it does Fizz
or Buzz
are returned. If divisible by both FizzBuzz
is returned. If divisible by neither, the Number is converted to a string and returned.