Conditional Statements

This article coversthe following concepts:

  • if, else if, and else statements
  • comparison operators
  • logical operators
  • ternary operators
  • switch statement

I. If, else if and else statements

  • if statement excecutes a block of JavaScript code if a condition is true.
  • We can add more conditions with else if statement.
  • We can add a default one with else statement.
if (condition1) {
  //  block of code to be executed if condition1 is true
} else if (condition2) {
  //  block of code to be executed if the condition1 is false and condition2 is true
} else {
  //  block of code to be executed if the condition1 is false and condition2 is false
}

Example

const x = 5;

if (x > 5) {
  console.log("x is greater than 5");
} else if (x < 5) {
  console.log("x is less than 5");
} else {
  console.log("x is 5");
}

II. Comparison Operators

To compare different values, we can use comparison operators.

  • Less than: <
  • Greater than: >
  • Less than or equal to: <=
  • Greater than or equal to: >=
  • Is equal to: ===
  • Is not equal to: !==

For example

if (time < 11) {
  greeting = "Good morning";
} else if (time < 18) {
  greeting = "Good afternoon";
} else {
  greeting = "Good evening";
}

III. Logical Operators

  • the and operator (&&) - both conditions are true
  • the or operator (||)
  • the not operator (!)
if (mood === "sleepy" && tirednessLevel > 8) {
  console.log("time to sleep");
} else {
  console.log("not bed time yet");
}

IV. Ternary Operator

We can use ternary operator to simplify an if…else statement.

  • The condition is provided before the ?
  • Two expressions follow the ? and are separated by a colon :
  • If the condition is true, the first expression executes
  • If the condition is false, the second expression executes
condition ? console.log("true") : console.log("false");
const x = 5;

const color = x > 5 ? "red" : "blue";

console.log(color); // blue

V. Switch statement

switch statement compares multiple values. It’s another way to evaluate conditions.

  • The case keyword checks if the expression matches the specified value that comes after it.
  • If none of the cases are true, then the code in the default statement will run.
  • The break keyword tells the computer to exit the block.
switch (expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
  // code block
}

Example

const x = 5;

const color = x > 5 ? "red" : "blue";

switch (color) {
  case "red":
    console.log("Color is red");
    break;
  case y:
    console.log("Color is blue");
    break;
  default:
    console.log("Don't know the color");
}