{
//execute this code if none of the above conditions were
true (in this case i is greater than 42)
}
·
The switch statement. The switch statement makes it easy to check the value of exactly
one variable without the need to write complex if-else statements:
var i = 42;
switch(i)
{
case 1:
//do something if i is equal to 1;
break;
case 2:
//do something if i is equal to 2;
break;
case 42:
//do something if i is equal to 42;
break;
case 48:
case 50:
//do something if i is equal to 48 or 50;
break;
default:
//do something if none of the above cases was true
break;
}
Note the break; statement in every case. If this is missing, the next case will also be
executed even if the case condition is not true (for values 48 and 50 the same code will
be executed). It is good practice to have a default case at the end of the switch. This
gets executed if no other case matched.
JavaScript also provides the typeof operator. With this the data type of a variable can be
checked:
var myNumber = 42;
var myString = "Hello World";
print("My number is of type " + (typeof myNumber) + ", my
string has type " + (typeof myString));
The return values of typeof are:
·
boolean
·
string
·
number
·
function
·
object
·
undefined