Selection

Objectives

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

// 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