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:
        ...    
}

Loops

The do-while Loop

A do-while loop executes the associated block at least once, then repeatedly while the conditional expression evaluates to true.

do {
    ...
} while (condition);

Below is an example of a do-while loop that print the numbers 0 – 10.

var counter = 0; 
do { 
    console.log(counter);     // prints 0 1 2 3 4 5 6 7 8 9     
    counter++; 
} while (counter < 10); 
console.log(counter);         // prints 10

The while Loop

In a while-loop, the conditional expression is evaluated and if true the block is executed and execution is redirected back to the conditional expression.  If the conditional expression evaluates to false, execution jumps to the line of code after the while-loop block.

while (condition) {
    ...
}

We can execute a while-loop a finite number of times using a counter variable as shown in the example below.

var counter = 0;
while (counter < 10) {
    console.log(counter);    // prints 0 1 2 3 4 5 6 7 8 9
    counter++;
}
console.log(counter);        // prints 10

The for Loop

The above while-loop example can be generalized as follows:

pre_loop_statement;
while(condition) {
    ...
    post_loop_statement;
}

This pattern is used so often, JavaScript (and other languages) provide a simplified construct for it called a for-loop.

for (pre_loop_statement; condition; post_loop_statement) {
    ...
}

The example above can be written using a for-loop as follows:

for (var counter = 0; counter < 10; counter++) { 
    console.log(counter);           // prints 0 1 2 3 4 5 6 7 8 9
} 
console.log(counter);              // prints 10

Recall that the let keyword restricts the scope of a variable.  If we don’t need to reference the variable defined in the pre_loop_statement outside the for-loop we should define the counter variable using let.

for (let counter = 0; counter < 10; counter++) { 
    console.log(counter);
}

The pre_loop_statement, condition, and post_loop_statement are optional but the semicolons are not.  For example, and infinite-loop can be written with a for-loop like this:

for(;;) {
    console.log("forever");
}

The for-in Loop

The for-in loop iterates over all of the keys of the properties of an object.

for (var key in object) {
    ...
}

The example below iterates over the properties of the object named player.

var player = {name: "Perry", score:900};
for (var key in player) {
    console.log(key);          // prints "name" and "score"
}

We can get the value associated with each key by dereferencing the key as shown below.

var player = {name: "Perry", score:900};
for (var key in player) {
    console.log(player[key]);     // prints "Perry" and 900
}

You should always check that the object is not null prior to executing a for-in loop on it.

The for-of Loop

The for-of loop iterates over all of the values of the properties of an iterable object.

for (var value of iterable_object) {
    ...
}

The example below iterates over the properties of the array named player.

var player = ["Perry", 900];
for (var value of player) {
    console.log(value);          // prints "Perry" and 900
}

Labels

Labels denote locations in code that can be jumped to with condition and break statements.  See below.

label:
...

The continue Statement

The continue keyword (without a label) redirects execution to the condition statement in the inner-most loop. The loop can be a for loop, a while loop, or a do-while loop.

for (...) {
    for (...) {        // After continue, execution jumps to condition statement here
        if (...) {
            continue;
        }
        ...
    }     
    ...        
}

A continue statement can also specify a label that is followed by a loop. When the continue statement is executed, execution jumps to the condition statement in the labeled loop.

outer_for_loop:        // label
for (...) {            // After continue, execution jumps to condition statement here
    for (...) {
        if (...) {
            continue outer_for_loop;
        }
        ...
    }
    ...             
}

The break Statement

The break keyword redirects execution to the next statement outside the inner-most loop.

for (...) {
    for (...) {
        ...
        if (condition) {
            break;
        }
        ...
    }                    
    ...       // After break, execution jumps here
}

A break statement can also specify a label that is followed by a loop. When the break statement is executed, execution jumps to the next statement outside the labeled loop.

outer_for_loop:    // label
for (...) {
    for (...) {
        ...
        if (condition) {
            break outer_for_loop;
        }
    }      
    ...              
}
...         // After break, execution jumps here