Conditional statements

Introduction

A conditional statement executes a set of statements if a specified condition is true. The conditional statements in JavaScript are if...else and switch. JavaScript also supports a conditional operator which can be considered a shorthand for a simple if...else statement. Also any switch statement can generally be replaced by a (chained) if...else statement, mostly at the cost of compactness or shortness, but not necessarily at the cost of clearness...

if...else statement

In general if...then or if...then...else statements are key elements of the structured control flow of computer programs. They are present in virtually all modern high-level programming languages, although the syntax varies from language to language. In JavaScript the basic syntax is:


if (condition)
  statement1
else
  statement2

The if...else statement executes statement1 if condition is truthy. If the optional else clause exists, statement2 is ignored.

If condition is falsy, statement1 is ignored and if the optional else clause exists, statement2 is executed.

In general, it is a good practice to always use block statements for statement1 and statement2.

The else if clause can be used to nest multiple if...else statements:


let age = 25;
if (age < 0){
  console.log("You don't exist");
} else if (age < 18){
  console.log("You are a minor");
} else if (age < 65){
  console.log("You are an adult");
} else if (age < 115){
  console.log("You are a senior");
} else {
  console.log("You are not human");
}
// logs: "You are an adult" 

switch statement


switch (expression) {
  case value1:
    // Statements
  case value2:
    // Statements
  ...
}

The switch statement evaluates expression and then looks for the first case clause whose value matches the expression's value, using strict comparison. It then executes all statements associated with that case, as well as all statements of all following cases.


let exp = 1,
    str = "Hello, ";
switch (exp) {
  case 0:
    str += "are "
  case 1:
    str += "you "
  case 2:
  case 3:	
    str += "OK?"
    console.log(str);
}
// logs: "Hello, you OK?" 

A break statement can be added after the statements associated with a case in order to break out of execution of the rest of the switch statement.


let message;
switch (new Date().getDay()) {
  case 1: // Monday
  case 2: // Tuesday
    message = "I wish it was weekend again!";
    break;  
  case 3: // Wednesday
    message = "We're halfway through the week!";
    break;
  case 4: // Thursday
  case 5: // Friday
    message = "Yippee, it's almost weekend!";
    break;
  case 6: // Saturday
  case 0: // Sunday  
    message = "😎😃";
}
console.log(message);

A default clause can be used to execute its associated statements if the value of the input expression doesn't match any of the case clauses. Mind that a previous match without a break will continue the execution of the switch statement, including a following default statement, if present.


let message;
switch (new Date().getDay()) {
  case 0:
  case 6:
    message = "Yippee, it's weekend! 😎😃";
    break; // without a break it will continue with the default statement.
  default: 
    message = "I wish it was weekend again! 😒";
}
console.log(message);

Result:

The statements associated with a particular case do not automatically form a block! For instance, a let variable declared anywhere within the switch statement has scope of the entire switch statement. This can be changed by wrapping the statements in a separate block, making it one block statement with its own block scope.


switch (new Date().getDay()) {
  case 0:
  case 6: {
    let message = "Yippee, it's weekend! 😎😃";
    console.log(message);
    break;
    }
  default: {
    let message = "I wish it was weekend again! 😒"; // declaring "let message" again, but within a different block scope.
    console.log(message);
    }
}

The conditional (ternary) operator

In cases where you only need the if statement without the else statement, you can consider a shorter syntax by using the short-circuiting property of the logical && operator. However, it is an operation instead of a statement. This means, for instance, that it returns false if 'the condition' is false, whereas an if statement returns nothing. As an equivalent, you can also use the conditional operator, aka the ternary operator.


let isLoggedIn = true;

if (isLoggedIn) { console.log("Hello, welcome again!") }
Is similar to:

let isLoggedIn = true;

isLoggedIn && console.log("Hello, welcome again!") // logs: "Hello, welcome again!"
Is equivalent to:

let isLoggedIn = true;

isLoggedIn ? console.log("Hello, welcome again!") : false // logs: "Hello, welcome again!"

The ternary operator also includes an "else" part:


let age = 25;
let message = (age < 18) ? "You are a minor" : "You are an adult";
console.log(message); // logs: "You are an adult"

Note that the return value of the operation is directly assigned to a variable (message).

The conditional operator is the only operator that takes three operands. This is why this operator is also known as the ternary operator (ternary = "composed of three items"). This operator can be considered a shorthand for a simplified if...else statement. The first operand is the condition, the second operand is the expression to be executed if the condition is truthy, the third operand is the "else expression". The operators are ? and :. The syntax is:


condition ? expression1 : expression2;

This is similar to:


if (condition)
  expression1
else
  expression2 

Note that, unlike in a if...else statement, expression1 and expression2 are not statements! So expression1 cannot be ended with a semicolon and neither expression can be a block statement. The conditional operator can be considered a shorthand for a "stripped down" if...else statement.


true ? { console.log('If, then this.') } : { console.log('else this.') }; // throws a SyntaxError

The ternary operator is right-associative, which means it can be "chained", similar to an if ... else if ... else if ... else nested chain.


let age = 25;
(age < 0) ? console.log("You don't exist") :
(age < 18) ? console.log("You are a minor") :
(age < 65) ? console.log("You are an adult") :
(age < 115) ? console.log("You are a senior") : console.log("You are not human");
// logs: "You are an adult"