Conditional Statements

This article coversthe following concepts:

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

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
}

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";
}

Logical Operators

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

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');

Switch statement

switch statement compares multiple values.

  • 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
}