CpSc 130 Notes Conditionals
if ( someTFexpression ) trueStatement ; |
Simplest conditional. The trueStatement is only executed if the condition is true (or the answer is yes). |
if ( someTFexpression ) trueStatement ; else falseStatement ; |
An if-else conditional. The trueStatement is executed if the condition is true (or the answer is yes), otherwise the falseStatement is executed. One of these is always executed. Never both. |
if ( someTFexpression ) ; trueStatement ; |
A common error — an errant semicolon. The semicolon ends the true part of the if statement with an unexpected result... the trueStatement is always executed. As far as JS is concerned, you said if someTFexpression is true, do nothing. Then continue with the next statement. (Indentation is for people. JS ignores it.) |
Either trueStatement or falseStatement (or both) may be empty statements indicating that nothing should be done for that condition. An if without an else is essentially such a statement where the falseStatement is empty. There are two ways to express an empty statement. The first uses the semicolon, the second a compound statement. Making both empty is a semantic error.
Note that this explains the error caused by the errant semicolon described above!
if ( someTFexpression ) ; // do nothing else falseStatement ; if ( someTFexpression ) trueStatement ; else ; // do nothing |
if ( someTFexpression ) { } // do nothing else falseStatement ; if ( someTFexpression ) trueStatement ; else { } // do nothing |
Some variables are of type Boolean and hold true/false values. They can be used in place of a logical expression in an if statement. But, what about numbers and strings? A number is considered to be false if the value is zero. A string is considered to be false if it is an empty string (""). Anything else is considered to be true.
switch ( varUsedToDecide ) { case firstValue : // statements for varUsedToDecide == firstValue break; case secondValue : // statements for varUsedToDecide == secondValue break; // any number of cases... default: // statements for when none of the cases match } |
Keywords are switch, case, break and default. The parenthesis and curly braces are required, as are the colons following each case. You may have any number of cases. The default is always last and covers "anything else". If you leave out a break in (for example) the first case, code for the second case will also be executed. In fact, it will continue executing code until a break is encountered. The break means "I'm done, leave the switch statement now." |