DEV Community

Cover image for Back to Basics: Conditional Statements in JavaScript
Alisa Bajramovic
Alisa Bajramovic

Posted on • Edited on

Back to Basics: Conditional Statements in JavaScript

This series discusses the building blocks of JavaScript. Whether you're new to the language, you're preparing for a technical interview, or you're hoping to brush up on some key JS concepts, this series is for you.

Today's post is about conditional statements:

What are conditional statements?

Conditional statements tell your program to do a certain set of commands if a certain condition is true. In JavaScript, there are if...else statements and switch statements.

Conditional statements are used all the time in the non-programming world. Let's say your friend asks you to pick them up some ice cream from the grocery store. They tell you, "If the store has mint chocolate chip ice cream, please get it. If the store doesn't have that, please get cookies and cream. If the store doesn't have that either, just get me chocolate ice cream." Written another way, your friend is saying:

  • If the store has mint chocolate chip ice cream: buy that.
  • Otherwise, if it has cookies and cream ice cream: buy that.
  • Otherwise: buy chocolate ice cream.

Each one of these statements has a condition ("the store has mint chocolate chip ice cream") and a statement to execute if that condition is true ("buy that"). It's also important to note that the order matters in these statements. Your friend doesn't want you to buy chocolate ice cream if cookies and cream is an option.

When working with conditional statements, it's important to keep in mind what you're checking, and what order things should be checked in.

If...else statements

An if...else statement is structured like the following:

if (condition) {
    statement_1;
} else {
    statement_2;
}
Enter fullscreen mode Exit fullscreen mode

If condition is true, then statement_1 will execute. Otherwise, if the condition is false, then statement_2 will execute.

It's important to note that the else clause is optional. Also, you can test multiple conditions in sequential order using else if:

if (condition_1) {
    statement_1;
} else if (condition_2) {
    statement_2;
} else if (condition_3) {
    statement_3;
} else {
    statement_last;
}
Enter fullscreen mode Exit fullscreen mode

When multiple conditions are being tested, only the first condition that evaluates to true is executed.

To execute multiple statements, group them in a block statement, like the following:

if (condition) {
    statement_1;
    statement_2;
} else {
    statement_3;
    statement_4;
}
Enter fullscreen mode Exit fullscreen mode

For example, let's say we have an array that keeps track of the temperature on each day of the week. If it's the end of the week (as in, the array has 7 temperatures in it), we want to report back that it's been a whole week. Otherwise, we want to log that it's not the end of the week yet:

let arr = [55, 60, 58, 57, 54];
if (arr.length === 7) {
  console.log("It's been a whole week!");
} else {
  console.log("It's not the end of the week yet.");
}
Enter fullscreen mode Exit fullscreen mode

Let's take that example a step further, and incorporate some of the loops we talked about in Back to Basics: Loops in JavaScript. Rather than just logging if it's the end of the week, we should return what the average temperate was that week.

There are multiple ways to find the average (or mean) of an array of numbers. One involves using a for loop to find the sum of every value of the array, and then dividing it by the length of the array (average is total sum divided by count). We'll start by initializing a variable which will equal the sum of every value in the array. Because we only want to find the average temperature of a full week, we will do this in the statement following the if condition.

let arr = [55, 60, 58, 57, 54, 52, 60];
if (arr.length === 7) {
  //initialize sum at 0 because we need to add values to it
  let sum = 0;
  //...
} else {
  console.log("It's not the end of the week yet.");
}
Enter fullscreen mode Exit fullscreen mode

Then, we can use a for loop to go over each value of the array, and add it to sum. The for loop will start a counter at 0, because arrays are zero-indexed in JavaScript. It will go until the length of the array, or arr.length. And we want to check each element of the array, one at a time, so we will increment by 1 each time. Inside of the for loop, we want to add the current value of the array to sum. We can access the value of the array with arr[i].

let arr = [55, 60, 58, 57, 54, 52, 60];
if (arr.length === 7) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    sum = sum + arr[i]; // this could also be written as sum += arr[i]
  }
  //...
} else {
  console.log("It's not the end of the week yet.");
}
Enter fullscreen mode Exit fullscreen mode

Once the for loop is done executing, sum contains the total sum of every temperate that week. Since we want to return the average temperature, we can divide sum by 7 (the number of days in the week), and console log that value.

let arr = [55, 60, 58, 57, 54, 52, 60];
if (arr.length === 7) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    sum = sum + arr[i]; // this could also be written as sum += arr[i]
  }
  console.log(
    "It's been a whole week! This week's average temperature was " +
      sum / 7 +
      "degrees."
  );
} else {
  console.log("It's not the end of the week yet.");
}
Enter fullscreen mode Exit fullscreen mode

Switch statements

The other kind of conditional statement supported in JavaScript is the switch statement. A switch statement evaluates an expression, and depending on that evaluation, tries to match it to a specified case. If a case matches, then that case's statement executes. A switch statement looks like the following:

switch (expression) {
    case label_1:
        statement_1;
        break;
    case label_2:
        statement_2;
        break;
    default:
        statement_default;
        break;
}
Enter fullscreen mode Exit fullscreen mode

First, expression is evaluated. Then, your program will look for a case whose label matches the value of the expression, and then the associated statement is executed. If no matching label can be found, your program will look for the default clause (which is optional), and executes the associated statement. If there is no default clause, your program will simply exit the switch statement.

The break statements tell your program to break out of the switch once that case's statement is executed. break statements are optional. If you don't include them, your program will stay in the switch statement, and will execute the next statement in the switch statement.

For example, let's say you're trying to decide what jacket to wear, and it depends on the weather. If it's hot, warm, or cold out, different jackets are appropriate:

switch (weather) {
  case "Hot":
    console.log("No jacket needed.");
    break;
  case "Warm":
    console.log("Bring a light jacket.");
    break;
  case "Cold":
    console.log("Bring your heavy jacket.");
    break;
  default:
    console.log("You probably should bring a jacket anyway, just in case!");
    break;
}
Enter fullscreen mode Exit fullscreen mode

You may be wondering, what exactly do the break statements do? Using the same example, let's say you didn't include any of the break statements, and that weather = "Hot":

let weather = "Hot";
switch (weather) {
  case "Hot":
    console.log("No jacket needed.");
  case "Warm":
    console.log("Bring a light jacket.");
  case "Cold":
    console.log("Bring your heavy jacket.");
  default:
    console.log("You probably should bring a jacket anyway, just in case!");
}
Enter fullscreen mode Exit fullscreen mode

The output would be:
No jacket needed. Bring a light jacket. Bring your heavy jacket. You probably should bring a jacket anyway, just in case!

This is because the label for the first case, "Hot", matches weather, so that statement executes. Then, each subsequent statement executes, since there are no breaks telling your program to stop.

The ternary operator

The ternary operator is not a type of conditional statement. Instead, it's an operator that checks a condition. It's a single line of code, and because it's so condensed, it's often used as a shortened version of a simple if...else statement.

The ternary operator is structured like the following:

condition ? expressionIfTrue : expressionIfFalse
Enter fullscreen mode Exit fullscreen mode

The condition is an expression that's evaluated. If condition is truthy (meaning that it is true, or its value can be converted to true), expressionIfTrue is executed. If condition is falsy (meaning that it is false, or its value can be converted to false, which includes null, NaN, 0, "", undefined), expressionIfFalse is executed.

For example, let's say the original if...else statement checks if a number is positive:

const num = 4;
if (num >= 0) {
  console.log("Positive");
} else {
  console.log("Negative");
}
Enter fullscreen mode Exit fullscreen mode

The condition is num >=0, which means that's what we're checking. Using a ternary operator, that will go on the left side of the question mark ?. If it's truthy, we'll want to console log "Positive", so that's the first expression after the ?. If it's falsy, we'll want to console log "Negative", so that's the second expression, and it comes after the colon :.

We can store the result of the ternary operator into a variable called positiveCheck. Then, we can console log the value of that variable.

const num = 4;
const positiveCheck = num >= 0 ? "Positive" : "Negative";
console.log(positiveCheck);
Enter fullscreen mode Exit fullscreen mode

Some people like ternary operators because they save space when working with simple conditional statements, but not everyone likes them or uses them. Whether or not you use ternary operators, it's important to know what they look like and how to read them in case you encounter them.


Please let me know in the comments if you have any questions or other ways of thinking about conditional statements in JavaScript.

Resources:

Top comments (0)