Switch Statements

Contact Us or call 1-877-932-8228
Switch Statements

Switch Statements

Rather than using a series of if/else if/else blocks, sometimes it can be useful to use a switch statement instead. switch statements are essentially a variable "goto" statement - the switch looks at the value of a variable or expression, and jumps to a matching labelled line within block controlled by the switch. At that point, all controlling behavior of the switch is done. All of the code after the matching label will be executed, even that belonging to later cases, unless you put in a break statement to exit the switch.

A switch Statement

switch (userResponse) {
	case 'yes':   // these cases are stacked - whichever one matches
	case 'yeah':  // will cause execution to fall through to the first
	case 'yowsa': // executable line below
	case 'yup':
		alert('Proceeding ...');
	break;        // now we exit the switch

	case 'no':
		alert('OK, bye!');
	break;

	default:
		alert('Sorry - I did not understand your response');
}
Next