JavaScript Switch Case Statement Example

The switch statement is used in JavaScript to evaluate cases for a variable and is used as follows:

var intTest = 1;
switch(intTest)
{
case 0:
document.write('0');
break;
case 1:
document.write('1');
break;
default:
document.write('unknown');
break;
}

The break statement exits the switch. If it is not used, subsequent cases will execute if also valid. For example, if no break was used in the case of 1 in the example above, both 1 and unknown would print.

The switch statement is preferable to multiple if statements as the tested value doesn’t have to be evaluated repeatedly.

String datatype example:

var strTest = 'a';
switch(strTest)
{
case 'a':
document.write('a found');
break;
case 'b':
document.write('b found');
break;
default:
document.write('unknown');
break;
}

2 Responses to “JavaScript Switch Case Statement Example”

  1. is the variable supposed to contain integers or are other data types possible?

  2. Other data types are certainly supported by the JavaScript switch statement.

    I have updated the post with a string datatype example.

Leave a Reply