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 = '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 < 5returnĀ 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!

Related Posts:


Tim profile image

A little about me..

Hey, Iā€™m Tim! šŸ‘‹

Iā€™m a freelance business owner, web developer & author. I teach both new and experienced freelancers how to build a sustainable and successful freelancing business. Check out myĀ Complete Guide to Freelancing if you'd like to find out more.

While you're here, you can browse through my blogs where I post freelancing tips, code tutorials, design inspiration, useful tools & resources, and much more! You can also join the newsletter, or find me on X.

Thanks for reading! šŸŽ‰