JS SWITCH

Standard

when there are a lot of choices that a program has to cover, instead of writing an else if statement each time, it’s possible to use the switch syntax

switch(expression){

case ‘ ‘:
// do things for this first case;
break;

case ‘ ‘:
// do things for this second case;
break;

default:
// do a default action if there is no matches;

switch allows you to preset a number of options (called cases), then check an expression to see if it matches any of them
if there is a match, the program will perform the action for the matching case
if there’s no match, a default option can be set and executed

var lunch = prompt(“what do you want for lunch?”,”sandwich, salad or pizza?”);

switch(lunch){

case ‘sandwich’:
console.log(“one sandwich, coming up”);
break;

case ‘salad’:
console.log(“sounds good, how about a caesar salad?”);
break;

case ‘pizza’:
console.log(“yummy, pizza”);
break;

case ‘pie’:
console.log(“pie’s not a meal”);
break;

default:
console.log(“huh, I’m not sure what ” + lunch + ” is”);
}

Advertisements

say something

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s