Selection
Objectives
- use if/else selection statements in JavaScript
- use switch selection statements in JavaScript
Selection structures
if (expr) {
... code executed if expr is true ...
}
if (expr) {
... code executed if expr is true ...
} else {
... code executed if expr is false ...
}
if (expr) {
... code executed if expr is true ...
} else if (expr2) {
... code executed if expr is false and expr2 is true ...
} else {
... code executed if expr is false and expr2 is false ...
}
switch (expr) {
case value1:
... code executed if expr==value1 ...
break;
case value2:
... code executed if expr==value2 ...
break;
.
.
.
default:
... code executed if no case values matched expr
}
An alternative: conditional
- The conditional operator "?:" takes three operands. If the first operand evaluates to
true, the entire expression assumes the value of the second operand. If the first
operand evaluates to false, the entire expression assumes the value of the third operand.
- The OR operator can be used to choose an alternative value for an expression if
a primary value evaluates to false.
// demonstration of conditional to get maximum value
var x = 7, y = 24;
var max = x > y ? x : y; // conditional: x > y ? x : y
// demonstration of using OR to choose an alternate value
var name = "" || "Unidentified";
// name will be "Unidentified" since first value evaluates to false
Examples