JavaScript Switch
JavaScript Tutorial » JavaScript Switch
The switch..case statement is an alternative to the if...else if...else statement, which does almost the same thing.
Syntax:
Example:
switch(x){
case value1:
// Code to be executed if x === value1
break;
case value2:
// Code to be executed if x === value2
break;
...
default:
// Code to be executed if x is different from all values
}
case value1:
// Code to be executed if x === value1
break;
case value2:
// Code to be executed if x === value2
break;
...
default:
// Code to be executed if x is different from all values
}
Consider the following example, which display the name of the day of the week.
Example:
var d = new Date();
switch(d.getDay()) {
case 0:
alert("Sunday.");
break;
case 1:
alert("Monday.");
break;
case 2:
alert("Tuesday.");
break;
case 3:
alert("Today is Wednesday.");
break;
case 4:
alert("Thursday.");
break;
case 5:
alert(" Friday.");
break;
case 6:
alert("Saturday.");
break;
default:
alert("No information available for that day.");
break;
}
switch(d.getDay()) {
case 0:
alert("Sunday.");
break;
case 1:
alert("Monday.");
break;
case 2:
alert("Tuesday.");
break;
case 3:
alert("Today is Wednesday.");
break;
case 4:
alert("Thursday.");
break;
case 5:
alert(" Friday.");
break;
case 6:
alert("Saturday.");
break;
default:
alert("No information available for that day.");
break;
}
Note: getDay() method returns the weekday as a number from 0 and 6
Multiple Cases Sharing Same Action - example
Each case value must be unique within a switch statement.
Example:
var d = new Date();
switch(d.getDay()) {
case 1:
case 2:
case 3:
case 4:
case 5:
alert("It is a weekday.");
break;
case 0:
case 6:
alert("It is a weekend day.");
break;
default:
alert("Enjoy every day of your life.");
}v
switch(d.getDay()) {
case 1:
case 2:
case 3:
case 4:
case 5:
alert("It is a weekday.");
break;
case 0:
case 6:
alert("It is a weekend day.");
break;
default:
alert("Enjoy every day of your life.");
}v
JavaScript Switch case, string, case return, multiple cases, case range, example, case string, return, ejemplo, or
JavaScript Switch case, string, case return, multiple cases, case range, example, case string, return, ejemplo, or
JavaScript Switch - javascript tutorial
Online Editor
This tool makes it easy to create, adjust, and experiment with custom colors for the web.
HTML Templates

Magnews2 is a modern and creative free magazine and news website template that will help you kick off your online project in style.
CSS HTML Layout

Find here examples of creative and unique website layouts.
Free CSS HTML Menu

Find here examples of creative and unique website CSS HTML menu.