Conditional statements
There are a few different ways to handle conditional
statements
. The first is the simple if
statement. It tests a condition and then, if the condition is met, it executes:
if( 2 < 1 ){ alert( 'Something is wrong' ); }
This same statement could also be written in shorthand (without the curly braces):
if( 2 < 1 ) alert( 'Something is wrong' );
If you wanted to know the outcome either way, you would use an if
...else
statement:
if( 2 < 1 ){ alert( 'Something is wrong' ); } else { alert( 'Everything is fine' ); }
You can also write this in shorthand, using what is called the ternary operator:
( 2 < 1 ) ? alert( 'Something is wrong' ) : alert( 'Everything is fine' );
The ternary operator functions like this:
(test condition
) ?statement if true
:statement if false
;
and can even be used for value assignment to variables:
var total = ( money > 1000000 ) ? 'over $1Million' : 'less than $1Million';
Now, suppose you wanted to know if one or more conditions were met. You could use an if
...else if
statement:
if( height > 6 ){ alert( 'You\'re tall' ); } else if( height > 5.5 ){ alert( 'You\'re average height' ); } else { alert( 'You\'re shorter than average' ); }
or a switch
statement:
switch( true ){ case ( height > 6 ): alert( 'You\'re tall' ); break; case ( height > 5.5 ){ alert( 'You\'re average height' ); break; default: alert( 'You\'re shorter than average' ); break; }
In each of these instances, a comparison is performed, and if the condition is not met, the next comparison ...
Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.