[Total: 1    Average: 2/5]

Javascript Reserved Word – SWITCH

SWITCH is a useful method to have multiple conditions set forth for
a given expression. An IF statement could be used
with ELSE IFs but the SWITCH is much easier
to organize and modify.

SWITCH is limited in that the condition to check the expression against must
be known at the time of the writting – variables can not be used… So if you
want to use variables to check your equation against … you will need to use
IF statements.

The basic syntax for an SWITCH statement:

switch (expression) {
[case ABC: [code;]+ [break;]]
default: break;

The expression is any valid javascript code that returls a boolean-like value.

These are the only values that return a boolean false value:

undefined, null, 0, false

All other things equate to a boolean true statement.

A small easy example:

switch(n) {

case 1: document.write(“1”);

case 2: document.write(“2”);

case 3: break;

case 4: document.write(“4”); break;

default: document.write(“?”); break;


If “n” evaluates to 1 or “1”, it will output “12”

if “n” evaluates to 2 or “2”, it will output “2”

if “n” evaluates to 3 or “3”, it will output “”

if “n” evaluates to 4 or “4”, it will output “4”

if “n” is any other thing – it will output “?”

Times Viewed: 51

Leave a Reply

Your email address will not be published. Required fields are marked *