The if statement has the following syntax:
if (condition) statement1 else statement2
The condition can be any expression. Javascript converts the expression into a Boolean using Boolean() function.
If the condition evaluates to true, statement1 is executed; if the condition evaluates to false, statement2 is executed.
In the following code the conditional expression
compares the value myAge
against a numeric value of 13
:
var myAge = 12;
if(myAge < 13) { //w w w . ja va 2 s .co m
console.log("under 13.");
}
var i = 3;
if (i){
console.log("true");
}else {
console.log("false");
}
The code above generates the following result.
You can also chain if statements together.
if (condition1) statement1 else if (condition2) statement2 else statement3
Here's an example:
var i = 50;
if (i > 25) {
console.log("Greater than 25.");
} else if (i < 0) {
console.log("Less than 0.");
} else {
console.log("Between 0 and 25, inclusive.");
}
The code above generates the following result.
The syntax for the switch statement in JavaScript:
switch (expression) { case value: statement break; case value: statement break; case value: statement break; case value: statement break; default: statement }
The following code:
if (i == 2){ console.log("2"); } else if (i == 3) { console.log("3"); } else if (i == 4) { console.log("4"); } else { console.log("Other"); }
can be rewritten as follows:
switch (i) { case 2: console.log("2"); break; case 3: console.log("3"); break; case 4: console.log("4"); break; default: console.log("Other"); }
Putting a break statement after each case avoids having cases fall through into the next one.
A fall-through case statement:
switch (i) { case 2: case 3: /* falls through */ console.log("2 or 3"); break; case 4: console.log("4"); break; default: console.log("Other"); }
The switch statement works with all data types and the case values need not be constants.
switch ("hello world") { case "hello" + " world": console.log("hello"); break; case "goodbye": console.log("see you"); break; default: console.log("Unexpected message was found."); }
Case expressions with comparison operators:
var num = 2; switch (true) { case num < 0: console.log("Less than 0."); break; case num >= 0 && num <= 10: console.log("Between 0 and 10."); break; case num > 10 && num <= 20: console.log("Between 10 and 20."); break; default: console.log("More than 20."); }
The switch statement compares values using the identically equal operator, therefore "10" is not equal to 10.
The with
statement sets the scope within a particular object.
The syntax is as follows:
with (expression) statement;
For the following code,
var qs = location.search.substring(1); var hostName = location.hostname;
The code above can be rewritten using the with statement:
with(location){ var qs = search.substring(1); var hostName = hostname; }
In strict mode, the with statement is not allowed and is considered a syntax error.