Booleans and Conditionals Part 1

Decisions, decisions, decisions ...

So far, the Javascript code we have seen has been executed unconditionally. When we wrote a sequence of statements, those statements were executed one after another, in order.

Many programming tasks, however, require conditional control, that is, the ability to react differently based upon some condition. For example, consider the task of assigning students' letter grades. Depending upon what the student's average is, a different letter grade must be assigned (e.g., 93 to 100 is an A, 86 to 93 is a A-, etc.). In this lesson, you will be introduced to booleans, truth values that represent a decision, and to the if statement, which performs conditional execution based on a boolean value. Based upon some condition, an if statement can choose among alternative sequences of code to execute, or even choose to execute no code at all.

Some examples, just to get us warmed up:

The following code asks a yes/no question ("ok" and "cancel") and does something on "yes":

The following code asks the same yes/no question and does something either way:

Those examples both used the confirm() function, which is like prompt() except that it returns a boolean value, namely either true or false.

Boolean Values

Before today, the JavaScript values we have seen are numbers and strings.

Today we meet the logical values true and false. These two values are called booleans. They are named after George Boole, a 19th century English mathematician who developed an algebraic framework for reasoning about the manipulation of truth values.

A boolean expression is any expression whose value is a boolean value. The simplest boolean expressions are the boolean literals true and false, which can be written directly in a JavaScript program. (They're not strings, so don't put them in quotation marks.) However, in a program, it is more typical for boolean values to be generated as the result of comparisons or other operations.

For example, relational operators on numbers produce boolean values. Put a number into the box below and click the "evaluate all!" button to see the boolean outcomes.

Expression Value Notes
num the meaning of the comparison in the first column
num < 50 less than
num <= 23 less than or equal to
num == 57 equal to (== tests equality, but = performs assignment!)
num != 17 not equal to
num > 110 greater than
num >= 42 greater than or equal to

Here are some examples of boolean expressions involving strings. Again, type a string into the box below (or use the default) and click the "Evaluate all!" button.

Expression Value Notes
str additional info about the comparison
str == "CS115 rocks!" == also tests equality of strings
str != "Grover" != also tests inequality on strings
str <= "CS111 is cool!" Strings are compared lexicographically (in dictionary order)
str > "CS24 isn't a course" Careful! Numbers in strings are also treated lexicographically.
str.length == 12 s.length returns the number of characters in s
str.indexOf("115") == 2 s1.indexOf(s2) returns the first (0-based) index of s2 in s1
str.indexOf("Rocks") == -1 indexOf returns -1 if string isn't found
str.charAt(1) == "S" s.charAt(i) returns the character at (0-based) index i in s
(In JS, a character is just a one-character string.)

if Statements

Conditional execution refers to the ability to execute a statement or sequence of statements only if some condition holds. The simplest form of conditional statement involves only one possible action. For example, displaying a message when the value of a variable is "Grover". However, conditional execution can also involve alternatives based on the same or related conditions. For example, we might want to display one message if the variable value is "Grover" and another message if it isn't. This type of conditional execution in JavaScript is performed using if statements.

The following example uses an if statement to greet Grover specially. Let's say we have gotten the name of the visitor stored in a variable first_name. The symbol == is used in JavaScript to test for equality (remember, just one = is for assignments!).

The following example uses the other form of an if statement to greet Grover and to be a bit hostile to everyone else.

In the first example, an alert box is displayed only if the condition (first_name == "Grover") holds. If the condition does not hold, then nothing special happens: the next JavaScript statement (if there is one) is evaluated.

The second example includes an else case which specifies the action to be taken when the condition does not hold (i.e., first_name is not equal to "Grover").

In an if-else statement, exactly one of the two actions will be executed.

In general, an if statement looks like this:

    if (BOOLEAN_EXPRESSION) {   // This is called the "test expression"
        STATEMENTS_IF_TRUE      // This is called the "then arm" or "then branch"
    } else {
        STATEMENTS_IF_FALSE     // This is called the "else arm" or "else branch"

The else part is optional.

Try an example here, testing whether a number is positive.

The test in an if statement can be any boolean expression, that is, any expression that evaluates to either true or false.

Exercise 1

Add an else case to the if statement so that it displays an appropriate message in the event that the number is not positive. Test your modified page on various inputs and list the results. What will be displayed when the number is 0?


  • The parentheses around the test expression in an if statement are mandatory. So you cannot write the following:
    if input_num > 0 { // missing required parens for test expression
         alert("the number is positive");
  • When there is only one statement in an arm of the conditional, the braces are optional. For example, the following is legal:
    if (input_num > 0) 
         alert("the number is positive"); // No braces for then arm

    However, we recommend that you always use braces to avoid bugs that come from adding more statements to the then arm.

© Wellesley College Computer Science Staff. This work is licensed under a Creative Commons License. Date Modified: Sunday, 28-Aug-2016 13:04:06 EDT