switch
Now that you understand a few more control structures, it’s time to revisit the switch
statement. As you saw in the previous switch
example, each case
within a switch
is tried and, if it matches the argument of the switch
, its statements are evaluated and the switch
is exited (via break
). There is also normally a default case
(simply called default
) that can act as a fallback (or an error alert) if none of the other case
s are met.
To demonstrate the power of the switch
, let’s spice up the countdown loop a bit:
for( var i=10; i >=0; i-- ){ switch( i ){ case 2: alert( 'Almost...' ); break; case 1: alert( 'There...' ); break; case 0: alert( 'BOOM!' ); break; default: alert( i ); break; } }
This code would initiate a countdown from 10 to 0, alert
-ing each number, but replacing 2 with Almost...
, 1 with There...
, and 0 with BOOM!
.
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.