DEV Community

Cover image for Understanding Conditional Statements in JavaScript
Esther Adebayo
Esther Adebayo

Posted on

Understanding Conditional Statements in JavaScript

Conditional statements execute specific actions from a code depending on whether the result of the code is true or false.

This means if a condition is true, a specific code runs and if false, another code runs.

If statement

The 'if' statement runs a specified code segment if the given result is ''true.''

This implies that the code block will be ignored in the case of a false result, and the code will move on to the next section.

let location = "outside";

if (location === "outside") {
  console.log("Wear your nose mask! 😷");
} 

//Output: Wear your nose mask! 😷
Enter fullscreen mode Exit fullscreen mode

Else statement

The 'else' statement is written after the if statement and executes the code if the result of the given condition is 'false'.

let location = "inside";

if (location === "outside") {
  console.log("Wear your nose mask! 😷");
} else {
  console.log("I don't need a nose mask 😃");
}

//Output: I don't need a nose mask 😃
Enter fullscreen mode Exit fullscreen mode

Else if statement

The 'else if' specifies another condition if the first condition is not true. They are used to add more conditions to an if/else statement.

let location = "inside";


if (location === "outside") {
  console.log("Wear your nose mask! 😷");
} else if (location === "inside") {
  console.log("I don't need a nose mask 😃");
} else {
  console.log("Always protect yourself");
}

//Output: I don't need a nose mask 😃
Enter fullscreen mode Exit fullscreen mode

Switch-case statement

This is a really cool way to execute different sets of statements based on the value of a variable. It is a neater version of multiple If-Else-If blocks.

A break is used between the cases & the default case gets evaluated when none of the cases are true

let location = "my room";


switch (location) {
  case "outside":
    console.log("Wear your nose mask!");
    break;
  case "my room":
    console.log("Yaay, I can relax 💆");
    break;
  default:
    console.log("Always protect yourself!");
}


//Output: Yaay, I can relax 💆
Enter fullscreen mode Exit fullscreen mode

Ternary Operator

The ternary operator is a shorthand syntax for an if/else statement.

The first expression after the ? executes when the condition evaluates to true, and the second expression after : executes when the condition evaluates to false.

const location = "outside";

location === "outside"
  ? console.log("Wear your nose mask! 😷")
  : console.log("Always protect yourself!");

Output: Wear your nose mask! 😷
Enter fullscreen mode Exit fullscreen mode

Thanks for reading. I hope you learned a thing or two. Which of these conditionals do you use?

Top comments (0)