Now that we’ve covered logic and comparison operators, we can use them to control the logic flow of our programs.
For example, if the time is before noon, we should display a “Good Morning!” message, but if it’s later in the day, “Good Afternoon!” or even “Good Evening!” would be more appropriate.
Conditional statements make this possible.
var d, hours, message; // Get the current time's hour and minute components d = new Date(); hours = d.getHours(); //0 .. 23 minutes = d.getMinutes(); //0 .. 59
if statements
//check time of day if (hours <= 12) { message = "Good morning!"; } //log message console.log(message);
else statements
//check time of day if (hours <= 12){ message = "Good morning!"; } else { message = "Good afternoon!"; } //log message console.log(message);
N-Way Branching
n-way branching can be done using a series of else-if statements (p. 72), or using a switch statement.
//check time of day if (hours > 0 && hours <= 12) message = "Good morning!"; else if (hours > 12 && hours <= 18) message = "Good afternoon!"; else message = "Good Evening!"; //log message console.log(message);
switch statements
The following is a switch statement (p. 72), perhaps the most error-prone control structure ever devised.
The “operand” after case can be any expression; it is compared via === with the parameter of switch.
//var day = Math.floor(Math.random() * 7); // 0..6 var day = d.getDay(); //0 .. 6 switch (day) { case 0: alert("Sunday"); break; case 1: alert("Monday"); break; case 2: alert("Tuesday"); break; case 3: alert("Wednesday"); break; case 4: alert("Thursday"); break; case 5: alert("Friday"); break; case 6: alert("Saturday"); break; default: alert("Error -- impossible value for day: " + day); break; }
Conditional Operator (?:)
A shorthand way of writing an if-else statement is to use the conditional operator (?:), from p. 71.
Because it is an operator (not a statement), it can be used where an if statement cannot. For example, in a console.log:
var die = rollDie(); console.log("You rolled an " + ((die % 2 == 0)? "even":"odd") + "