17.7 Conditional Statements in JavaScript
Conditional statements or branches allow you to influence the flow of the program by defining a condition and thus deciding at which point the program should be continued. The following options are available to you:
-
You can use if to branch to a block of statements that are executed only if the condition in the parentheses of if() equals true. This is also called a conditional branch.
-
You can use else with a block of statements that will be executed only if the previously checked if condition was equal to false.
-
else if can be used with a block of statements to test another condition if the preceding if was equal to false. After a preceding if, you can use multiple else if conditions. Alternatively, you can use switch() for such a multiple branch.
In your daily work, you’ll probably use conditional branching with if and the alternative else most often. Here’s the syntax of such an if-else construct:
if ( condition==true ) {
// statements if condition is true
}
else {
// statements if condition is false
}
As a condition itself, you can use any expression that can be evaluated to a Boolean truth value. I’ll describe the Boolean truth value in the next section. At this point, it should be noted that the alternative else branch is optional here.
Statement Blocks
You already know a block with statements (or statement block) from the functions; that is, several statements are combined in one block. Such a block starts with an opening curly bracket ({) and ends with a closing curly bracket (}). JavaScript doesn’t require a semicolon at the end of the curly bracket.
17.7.1 “true” or “false”: Boolean Truth Value
A Boolean truth value is specified as true or false in JavaScript. Simply put, it can be said that anything containing a true value equals true, and anything without a true value is false. Nevertheless, JavaScript isn’t limited to the Boolean values true and false. There are also values that are considered false (also called falsy), such as undefined, null, 0, or "". Such falsy values are treated as false. Other values that aren’t falsy, on the other hand, are considered true and are truthy. Thus, objects (without properties), functions, or arrays (with length 0) are truthy. This means that "" is equal to falsy, and " " is truthy. Arrays are described separately in Chapter 18, Section 18.2.
Real values and therefore true are the following examples:
1234
1.234
-1
"A text"
5 + 1 * 2
Here’s an example for demonstration purposes:
let mytext = 'A text';
if (mytext) {
console.log('"mytext" is a valid value.'); // <- Output
} else {
console.log('"mytext" is an invalid value.');
}
Here, the if condition equals true, so mytext is a valid value, which is why the corresponding output is executed in the curly brackets following it.
The following examples have no real values and therefore are always false:
0 // The number 0 is false.
"" // An empty string is false.
var val01; // Empty variable is undefined and therefore false.
var val02 = false;
100 / "text" // is NaN (= Not a Number), therefore false
null // null is always false.
NaN // Not a Number, no number is false.
Here’s another example:
let mytext = "A text";
let val01 = 100;
if (val01 / mytext) {
console.log('Calculation successful');
} else {
console.log('NaN -> no valid value.');
}
Here the statements would be executed in the alternate else block because the if condition returns false. The division of 100 / "A text" results in the symbolic value NaN (NaN = not a number) and is therefore invalid and false.
17.7.2 Using the Various Comparison Operators in JavaScript
Besides the possibility to check whether a value is valid and equals true or just an invalid value and thus returns false, you can compare variables and values using the various comparison operators. Depending on whether the comparison is true or false, true or false will be returned here as well. To perform comparisons, JavaScript provides the comparison operators listed in Table 17.4.
|
Operator |
Description |
Example (x=6; y=5) |
|---|---|---|
|
== |
Same as |
x==5; // false |
|
!= |
Unequal to |
x != 5; // true |
|
=== |
Same value and type |
x === y; // false |
|
!== |
Different value or different type |
x !== y; // true |
|
> |
Greater than |
x > y; // true |
|
< |
Less than |
x < y; // false |
|
>= |
Greater than or equal to |
x >= y; // true |
|
Less than or equal to |
x <= y; // false |
Table 17.4 Comparison Operators in JavaScript
17.7.3 Using the “if” Branch
With the background knowledge of Boolean truth values and the comparison operators, you’ll be able to apply the if branches in practice. Let’s take a look at a simple example:
let age = prompt('How old are you: ');
if (age >= 18) {
console.log("Access granted")
} else {
console.log("Access denied");
}
When you run the example, the prompt() method opens a dialog in the browser window with an input field and an OK and Cancel button. The value you enter here in the input field is returned by prompt() and assigned to the variable age in the example. The if statement then checks whether the value of the variable age is greater than or equal to 18. If this condition is true, a corresponding output will appear in the console. If the condition is false, the statement is executed in the alternate else branch.
At this point, I’d like to share a few words about the comparison operators === and !==. These are necessary because with comparison operators, an implicit type conversion is performed before the comparison so that these values can be compared. In the following example, a string is compared to an integer:
let strVal = "1234"; // number
let iVal = 1234; // string
if (strVal == iVal) { // true because type conversion
console.log("Both values are equal");
} else {
console.log("Values are different")
}
In this example, the comparison of "1234"==1234 returns true due to a type conversion. For such purposes, the operators === and !== are available, which compare not only the value but also the type. So, if you replace the == operator with the === operator in the example, true will no longer be returned because the value is the same but the type isn’t.
17.7.4 Using the Selection Operator
You can shorten an if-else construct with the selection operator. This is very useful, for example, if you want to assign a specific value to a variable depending on the condition. The structure of the operator is as follows:
let val = condition ? value1 : value2;
Here the value1 value is assigned to the variable val if condition is true. If condition is false, the value2 will be assigned to val. With regard to the if-else construct, this roughly corresponds to the following:
let val;
if (condition) {
val = value1;
} else {
val = value2;
}
The else branch can be omitted if val is initialized with false at the beginning. However, this is also more about demonstrating the counterpart of the selection operator.
Here’s an example of the selection operator, where prompt() is used to query a pseudo password, and according to the input, true or false gets assigned to the isAdmin variable:
let pwd = prompt('Enter password: ');
let isAdmin = pwd == 12345678 ? true : false;
console.log(isAdmin);
17.7.5 Logical Operators
The logical operators in JavaScript are && (AND), || (OR), and ! (NOT). Logical operators are used with truth values. If you use numbers, they will be implicitly converted to a truth value before they are linked with &&, ||, or !.
|
Operator |
Meaning |
|---|---|
|
&& |
Expressions linked with the AND operator return true only if all expressions are true. Example: if ( ival1 > 0 && ival2 > 0 ) { |
|
Expressions combined with the logical OR operator return true if at least one of the expressions is true. Example: if ( ival1 > 0 || ival2 > 0 ) { |
|
|
! |
You can use the logical NOT operator to negate an expression. So, you can turn “true” into “false” and vice versa. Example: if( !(ival > 0) ) { |
Table 17.5 The Logical Operators in JavaScript
Here’s a simple example in which you’re again supposed to enter a value between 1 and 100 via the prompt of a prompt() dialog:
let val = prompt('Enter a value from 1 - 100: ');
if (val >= 1 && val <= 100) {
console.log("The value matches the requirements.")
} else {
console.log("Wrong input: " + val);
}
Using the logical AND, the expressions of whether the entered value val is equal to or greater than 1 AND equal to or less than 100 have been linked here, and true will only be returned if both expressions are true.
If you had used the logical OR operator || instead, true would always be returned if the entered value is greater than or equal to 1 because the second expression wouldn’t have been checked at all. However, if the value is negative or 0, the OR operator in the example also evaluates the second expression. In the case of a link with the logical OR, the check aborts at the first true because the condition is that at least one link is true.
Linking More Expressions Together
Of course, you can link more than two expressions together or mix the && and || operators. However, you should keep in mind the readability of the source code.
17.7.6 Multiple Branching via “switch”
If you want to check multiple cases, you can theoretically use multiple if queries in a row, or you can use the case distinction, switch. In JavaScript, switch supports values with any type. It’s even possible to have values determined dynamically first via function calls. In many other programming languages, these values must be constants. For this purpose, here’s a theoretical construct of a switch case distinction:
switch( expression ) {
case label_1:
statements;
[break];
case label_2:
statements;
[break];
...
default:
statements;
}
In this case distinction, a matching value in case is searched for the expression in switch. If a case marker matches the switch evaluation, the program execution takes place after this case marker. If no case marker matches the switch evaluation, you can use an optional default marker, which will be executed as an alternative. Of particular importance in a switch case distinction are the break statements at the end of a case marker. You can use break to instruct the program to jump out of the switch block and continue with the program execution after. If you don’t use a break statement, all further statements (including the case markers after them) in the switch block will be executed until the next break statement or the end of the block has been reached.
Here’s a simple example to demonstrate switch in use:
switch (new Date().getDay()) {
case 0:
console.log("Today is Sunday");
break;
case 6:
console.log("Today is Saturday");
break;
default:
console.log("Today is an ordinary weekday");
}
Here, a Date object is created in switch, which is why the getDay() method is called. The getDay() method returns a day of the week as a number. 0 is returned for Sunday, 1 for Monday, and so on to 6 for Saturday. In the example, the return value is compared with case markers 0 (for Sunday) and 6 (for Saturday). If one of the markers matches, a corresponding output will occur in the JavaScript console. If none of the case markers apply, the return value is 1, 2, 3, 4, or 5, and it’s a normal weekday, so that no case marker will be used here anymore but default.