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.
if
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.
confirm()
prompt()
true
false
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.
==
=
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.
!=
s.length
s
s1.indexOf(s2)
s2
s1
indexOf
s.charAt(i)
i
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.
"Grover"
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!).
first_name
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.
(first_name == "Grover")
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").
else
In an if-else statement, exactly one of the two actions will be executed.
if-else
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.
let num = parseFloat(prompt("Enter any number")); if (num > 0) { alert("the 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.
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?
let num = parseFloat(prompt("Enter any num")); if (num > 0) { alert("the number is positive"); }
if input_num > 0 { // missing required parens for test expression alert("the number is positive"); }
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.