Conditional Statements

Conditional statements include an expression that can be evaluated as a Boolean and a block of code.   If the boolean expression evaluates to true, the block of code is executed.  Otherwise execution jumps to the next line of code after the block.

In JavaScript, the boolean expression can be a non-Boolean variable since all values can be evaluated as a Boolean.  See the table below for how variable values are evaluated as Booleans.

Data Type Values converted to true Values converted to false
Boolean true false
String Any nonempty string “”
Number Any nonzero number 0 or NaN
Object Any nonnull object null
Undefined undefined

A block is declared with opening and closing curly braces.  They can be omitted if the block contains a single statement – though it is good programming style to always include curly braces.

The if-else Statement

Only one block is executed in an if else-if else statement; the block associated with the first conditional expression that evaluates to true.  If the statement has an else block and no conditional express evaluates to true, then the else block is executed.

if (condition) {
     ...
}
else if (condition) {
    ...
}
else {
    ...
}

The example below illustrates that a String can be used as a conditional expression.

var name = "Sarah";
if (name) {
    console.log(name);
}

The switch Statement

Switch statements compare the value of an expression to the values of various cases.  If the expression is equal to the value of a case, the code between the colon and the first break statement encountered after the colon is executed.  If the switch statement includes a default case and the expression does not equal any of the values of the cases, the code that follows the default case’s colon is executed.

switch (expression) {
    case value:
        ...
        break;
    case value:
        ...
        break;
    ...
    default:
        ...    
}

© 2018, Eric. All rights reserved.