JavaScript Tutorial – Conditional Statements

Back to IT Blog - The latest and most important web solutions in information technology

JavaScript Tutorial – Conditional Statements

When we want to introduce logic & make decisions in our programs using JavaScript, 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 elsestatements. 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 the 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 the variable will be set to “It is AM” if the is less than 12. Otherwise 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 falseundefinednull0NaN, 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/elsestatements, 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 us 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  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 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).

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

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!

I hope you found this article useful! You can follow me on Medium. I’m also on Twitter. Feel free to leave any questions in the comments below. I’ll be glad to help out!

 


How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

As you found this post useful...

Follow us on social media!

Share this post

Back to IT Blog - The latest and most important web solutions in information technology