Conditional Statements

What are Conditional Statements?

Conditional statements let your code make decisions based on logic or values. They control flow by deciding what code runs and when. They key conditionals are if, else if, and else.

if (condition) {
    // code to execute if true
} else if (condition) {
    // code to execute if first condition is false but this condition is true
} else {
   //  code to execute if other conditions are false
}

You can chain multiple else if blocks, but only the first true block will run.

There is a shorthand for checking for truthiness (Values like 0, "", null, undefined, and NaN are all falsy. Everything else is truthy).

if (variable) {};

Ternary Conditionals

Ternary conditionals are shorthand versions of if/else statements. The basic syntax is condition ? valueIfTrue : valueIfFalse;.

if (codeblock) {
    blockstatement1;
} else {
   blockstatement2;
}

// Becomes
(codeblock) ? blockstatement1 : blockstatement2; 

Comparison Operators

Symbol Meaning Example
< Less than. x<10;
<= Less than or equal to. x<=10;
> Greater than. x>5;
>= Greater than or equal to. x>=6.
=== Strict equality. x==="5";
!== Strict inequality. x!=="5";
&& Logical AND. A&&B;
! Logical NOT. !A

Always use === and !== instead of == or != to avoid type coercion bugs.

Switch

In the case of multiple else if statements, a switch might make more sense. An example of this is checking if a percentage grade is an A, B, C, D, E etc. They follow the general structure of:

switch (true) {
    Case 1:
        Blockstatement
        Break
    Case 2:
        Blockstatement
        Break
    Etc
    default:
        Blockstatement
}

The final option is default which covers the else case and it has no break clause. The break clauses make the computer take that case if it matches and skip the rest. You'll notice it starts with switch (true) which will evaluate the cases against.

// Before
let result = 75;

if (result > 79) {
    console.log("A");
} else if (result>69) {
    Console.log ("B");
} else {
    Console.log("C");
}

// After
let result = 75;

switch (true) {
    case (result > 79):
        console.log("A");
        break;
    case (result > 69):
        console.log("B");
        break;
    default:
        console.log("C");
}

If you want to achieve an "or" statement in a switch, you can stack the cases above one block statement. The following will log “This is a pome fruit”.

let fruit = "apple";

switch (fruit) {
    case "apple":
    case "pear":
        console.log("This is a pome fruit.");
        break;
    case "orange":
    case "lemon":
    case "lime":
        console.log("This is a citrus fruit.");
        break;
    default:
        console.log("Unknown fruit.");
}