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 {
}
``````

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 = 'Cheetos';

if (snack) {
console.log('I have Cheetos!');
} else {
console.log('No Cheetos 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 === 'Cheetos') {
if (hungerLevel > 5) {
console.log('My hunger level is' + hungerLevel + ' and I have Cheetos. So I will eat them!');
} else if (hungerLevel <= 5) {
console.log('My hunger level is' + hungerLevel + ' and even though I have Cheetos. 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 toÂ `true`Â for the whole expression to returnÂ `true`.

Let's rewrite our previous example using AND:

``````if (snack === 'Cheetos' && hungerLevel > 5) {
console.log('My hunger level is' + hungerLevel + ' and I have Cheetos. So I will eat them!');
} else if (snack === 'Cheetos' && hungerLevel <= 5) {
console.log('My hunger level is' + hungerLevel + ' and even though I have Cheetos. I\'m not that hungry so I won\'t eat them yet!');
}
``````

The first code block will only run ifÂ `snack === 'Cheetos'`Â 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:

``````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.

## Conclusion

And thatâs it! 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!