Skip to content

Conditional Statements

jfraboni edited this page Jan 4, 2015 · 1 revision

###Making Decisions

In a programming paradigm, we control the flow of an application by asking the runtime to make decisions based on whether a condition is true or false. These switches in logic, similar to switches on a train track, are sometimes called control flow or conditional statements.

Essentially, we ask the interpreter to evaluate an expression that boils down to a Boolean value, true or false. These expressions can be complex, too. The path of execution, that is, what portion of code is executed, can be decided based on the result of the evaluation.

In JavaScript, we have certain control-flow constructs that help us do just this: control what code is executed and what is code skipped. They are combinations of if and else statements, while and do-while statements, as well as switch statements:

Table of Contents

Code and Quiz

Code a little

Take the quiz

Comparison Operators

The real magic of conditional statements is possible because of comparison operators. Comparison operators give us the ability to compare values against each other. A comparison operation returns one of two values: true or false, and from this outcome, we can make decisions about what code we want to execute, and what code we want to skip.

Comparing Equality

While the single equal character of = is an assignment operator, assigning the value on the right to the identifier (variable or constant or let) on the left, the double and triple equal character of == or === are comparison operators, checking equivalance between to values.

console.log(1 === 1); // prints true

Here, we're strictly comparing two numbers, 1 and 1, which are strictly equal, so their comparison returns true.

The difference between a double equal comparison and triple equal is that the latter strictly compares two values, including the datatype of the values. Non-strict comparison of the string "1" and the number 1 will return true; strict comparison of these two values will return false:

console.log("1" == 1);   // non-strict equality comparison using ==, prints true
console.log("1" === 1);  // strict equality comparison using ===, prints false

Because of this, you should probably use strict comparison unless there's good reason not to do so.

To compare inequality, we use != and strictly, !==:

console.log("1" != 1);   // non-strict inequality comparison using !=, prints false
console.log("1" !== 1);  // strict inequality comparison using !==, prints true

Above, the string value of "1" is non-strictly equal to the number 1, so the comparison of "1" != 1 returns false. But the strict comparison of "1" !== 1 returns true, because the type String and Number cannot be equal.

Comparing Relation

We can also compare values on the level of relationship, for instance, is one value greater than another, or is a value greater than or equal to another. Here's some examples:

console.log(1 < 2);  // less than, prints true
console.log(1 > 2);  // greater than, prints false
console.log(1 <= 2); // less than or equal to, prints true
console.log(1 >= 2); // greater than or equal to, prints true

console.log(2 >= 2); // greater than or equal to, prints true

Logical Operators

Logical operators give us the ability to chain together comparisons by using the and (&&) and the or (||) operators.

console.log(1 === 1 && 1 < 2);   // prints true
console.log(1 > 2 || 3 === 3);   // prints true

Using the && operator, we ask if 1 is strictly equal to 1 and if 1 is less-than 2: given that both statement are true, the expression evaluates to true. Next, using the || operator, we ask if 1 is greater-than 2 or 3 is strictly equal to 3.

There are many types of comparison operators, and you'll get to use them all in your programming. Check out this detailed discussion for more information. An understanding of comparison operators will help you make decisions in your applications, as they are the mechanism powering conditional statements.

Alright, on to the types and syntax of conditional statements...

The if Statement

You want to do something if and only if something is true. The if statement is your tool!

####Syntax

The syntax of the if statement consists of the keyword if followed by parenthesis that contain an expression, followed by a code block that will execute if the expression evaluates to true or false, somelike like if (score > highScore) { // code block }

var isTrue = true;

if (isTrue) {
    // do something ... //
}

Above, the Boolean isTrue was set to true, and thus evaluates to true in the conditional statement, so the code block will execute.

The if ...else Statement

You want to do something if and only if something is true, or else, you want to do something else. In short, do this or do that!

####Syntax

The if ...else builds on the if statement to include a code block marked by the keyword else. The else code block will execute if the conditional check of the if statement returns false:

var highScore = 20;
var score = 10;

if (score > highScore) {
    console.log('You set a new high score %d', score);
    highScore = score;
} else {
    console.log('Your score of %d did not beat the high score of %d.', score, highScore);
}

In the above example, value of score is less than the value of highScore, so the code block of the else statement is executed, and we print 'Your score of 10 did not beat the high score of 20.'. If the first conditional statement equates to false, by default, the else block will execute.

The if ...else-if Statement

You want to do something if and only if something is true, or, if and only if something else is true!

####Syntax

if ...else-if allows us to chain together as many conditional statements as we need. Following the first if statement, we append the keywords else if, followed by another comparison in parenthesis, followed by a code block to be executed if the else if comparison returns true:

var grade = 'a';

if (grade === 'a') {
    console.log('Wow, well done, you scored an %s!', grade);
} else if (grade === 'b') {
    console.log('Pretty good, you scored a %s.  Review and try again!', grade);
}

Above, we're asking if grade is strictly equal to a, and if not, we then ask, using another comparison, if the grade is strictly equal to b. We could keep going with ...else-if statements, checking the value of lesser grades.

The if ...else-if ...else Statement

You want to do something if and only if something is true, or, if and only if something else is true, or, if none of the above are true, do some default action.

####Syntax

We simply add a trailing else block to our if ...else-if statement:

var grade = 'c';

if (grade === 'a') {
    console.log('Wow, well done, you scored an %s!', grade);
} else if (grade === 'b') {
    console.log('Pretty good, you scored a %s.  Review and try again!', grade);
} else {
    console.log('You score a %s! You can do much better!  Please review and try again!', grade);
}

Here, we provide a default in the final else statement for grades other than a or b.

The switch Statement

The switch statement is essentially the same logic as the if ...else-if ...else statement, only perhaps more legible.

####Syntax

The switch statement is defined using the switch keyword. The switch takes a value to switch-on, specified within parentheses, and then we define which cases we want to handle, with an optional default case. The default case will be executed if no other cases are matched against the switch value. Each case block expects a break keyword to signify when the case code is to stop executing. Failing to provide the break statement will cause subsequent cases to fire and unexpected results to occur, so make sure you include your breaks:

var input = 1;
switch (input) {
    case 1:
        console.log('The input was 1');
        break;
    case 2:
        console.log('The input was 2');
        break;
    default:
        console.log('The input was unexpected');
        break;
}

© 2014-2015 Operation Spark