The Basics of JavaScript Conditionals
How to Use Conditionals (if, else, else if) in JavaScript
When we want to introduce logic & make decisions in our programs, we use conditionals. With conditionals, we can control the behavior of our code — by determining whether or not pieces of code can run.
For example, when using a weather app, if the weather is sunny we could see a sun image, or if it's raining we could see a rain-cloud image. Let’s now take a look at how we can implement conditionals in our code.
if/else Statements
The most common type of conditional statements are if
and else
statements. The syntax looks like so:
if (condition) {
run this code if the condition is true
} else {
run this code instead
}
We use if
followed by a set of parentheses that contain our condition. The condition will make use of comparison operators to test whether our condition evaluates to true
or false
, and it’ll return the result.
If the result is true
, the code in the following set of curly braces will execute. The code in this section can be whatever we like.
If the result is false
, the code contained within the curly braces following our else
statement will execute instead.
Let’s take a look at an example:
if (hour < 12) {
notify = "It is AM";
} else {
notify = "It is PM";
}
In our above code, our notify
variable will be set to “It is AM” if the hour
is less than 12. Otherwise hour
is greater than 12 and will be set to “It is PM”.
else if
Of course, we will often have more than two choices to work with! To consider these additional choices we use else if
. We put additional blocks in between our if () {}
and else {}
statements. Let's adjust our previous example to see this in action:
if (hour < 12) {
notify = "It is Morning";
} else if (hour < 19){
notify = "It is Afternoon";
} else {
notify = "It is Evening";
}
Comparison Operators
To test the conditions inside our conditional statements, we use comparison operators. These operators are as follows:
===
and!==
— to test if one value is equal to, or not equal to, the other.<
and>
— to test if one value is less than or greater than the other.<=
and>=
— to test if one value is less than or equal to, or greater than or equal to, the other.
A very common pattern when doing comparisons in conditional statements is to test Booleans (true
and false
). Any value that is not false
, undefined
, null
, 0
, NaN
, or an empty string ('')
will in fact return true
when tested as a conditional statement. This means you can easily use a variable name on its own to test whether it is true
, or even that it exists at all (i.e. it is not undefined.) For example:
let snack = 'Pretzels';
if (snack) {
console.log('I have Pretzels!');
} else {
console.log('No Pretzels this time..');
}
Nesting if/else
There will be times when you’ll want to nest an if/else
statement inside of another one — and it's fine to do so! Let’s see an example:
if (snack === 'Pretzels') {
if (hungerLevel > 5) {
console.log('My hunger level is' + hungerLevel + ' and I have Pretzels. So I will eat them!');
} else if (hungerLevel <= 5) {
console.log('My hunger level is' + hungerLevel + ' and even though I have Pretzels. I\'m not that hungry so I won\'t eat them yet!');
}
}
Logical Operators: AND, OR, and NOT
We can also test multiple conditions without needing to write nested if/else
statements, we do this with logical operators:
AND: &&
- lets you chain together two or more expressions. Every expression must evaluate as true
for the whole expression to return true
.
Let's rewrite our previous example using AND: ``js if (snack === 'Twizzlers' && hungerLevel > 5) { console.log('My hunger level is' + hungerLevel + ' and I have Twizzlers. So I will eat them!'); } else if (snack === 'Twizzlers' && hungerLevel <= 5) { console.log('My hunger level is' + hungerLevel + ' and even though I have Twizzlers. I\'m not that hungry so I won\'t eat them yet!'); }
The first code block will only run if `snack === 'Twizzlers'` _and_ `hungerLevel < 5` return `true`.
**OR**:`||`- also lets you chain together two or more expressions. One or more of them have to evaluate to `true` for the whole expression to return `true`.
Let’s see an example using OR:
```js
if (trafficLightIsGreen || carStatus === 'working') {
console.log('You should commence driving.');
} else {
console.log('Might be an issue.');
}
NOT: !
- can be used to negate an expression. Let's combine it with OR in the above example:
if (!(trafficLightIsGreen || carStatus === 'working')){
console.log('You should commence driving.');
} else {
console.log('Might be an issue.');
}
In this example, our OR statement returns true
, however, the NOT operator will negate it - so that the overall expression now returns false
.
A common mistake when using the logical OR operator in conditional statements is to try to state the variable whose value you are checking once, and then give a list of values it could be to return true, separated by ||
(OR) operators. For example:
if (x === 10 || 20 || 30 || 40) {
// run this code
}
In this case, the condition inside if(...)
will always evaluate to true since 20 (or any other non-zero value) always evaluates to true. This condition is actually saying "if x equals 10, or 20 is true — which it always is". This is logically not what we want! To make this work you've got to specify a complete test on either side of each OR operator:
if (x === 10 || x === 20 || x === 30 || x === 40) {
// run this code
}
Switch Statements
if/else
statements do a great job of enabling conditional code, but they are not always the best way to handle every scenario. They are mainly useful when you've got a couple of options, and each one requires a reasonable amount of code to be run. They’re also useful when the conditions are complex (e.g. multiple logical operators).
For cases where you just want to set a variable to a certain choice of value or print out a particular statement depending on a condition, the syntax can be a bit inefficient, especially if you've got a large number of choices.
This is when we should consider using a switch
statement! — they take a single expression/value as an input and then look through a number of choices until they find one that matches that value, executing the corresponding code that goes along with it. Let’s see an example:
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
We use the keyword switch
, followed by a set of parentheses that contains our expression. This is followed by the keyword case
, followed by a choice that the expression/value could be, followed by a colon. We then include some code to run if the choice matches the expression. And finally a break
statement.
If the previous choice matches the expression/value, the browser stops executing the code block here and moves on to any code that appears below the switch statement. We can include as many other cases as we need!
Ternary Operator
In this final section of the article, let's take a look at the ternary operator. It’s a small piece of syntax that tests a condition and returns one value/expression if it’s true
, and another if it's false
— this can be useful in some situations and takes up a lot less code than an if/else
block. The pseudocode looks like this:
( condition ) ? run this code: run this code instead
So let’s look at a simple example:
let age = 25;
let beverage = (age >= 18) ? "Beer" : "Apple Juice";
console.log(beverage); // "Beer"
If age
is true
, the customer can buy a beer, if not, all we have to sell them is apple juice.
Summary
We’ve learned all about how we use conditionals to make decisions in our code. By using if, else and switch statements, combined with comparison, logical and ternary operators — we’re well equipped to introduce logic into our programs!
Conclusion
If you liked this blog post, follow me on Twitter where I post daily about Tech related things!