MENU
Conditional Branching
The execution flow of statements may be controlled by if:
if (condition) statement1; [else statement2;]
If (condition) evaluates to true, statement1 will be executed; otherwise, statement2 will be executed.
Notice that the else part is optional.
If there are more than one statements, they must be contained by {...}:
if (condition){statements1;}[else {statements2;}]
Sometimes conditional statements can be shortened with switch:
switch(expression){case value1: statements1; break; case value2: statements2; break; case value3: statements3; break; ......default: statements4; }
The expression, usually a variable, will be evaluated once only.
The use of break prevents the execution from flowing into the next block.
The statements after default are executed if the expression does not match any of the values specified by case.
if (a + b == c)
x = "car";
else if (a + b == d)
x = "bus";
else {
x = "nothing";
v = "restart";
}switch (a + b) {
case c:
x = "car";
break;
case d:
x = "bus";
break;
default:
x = "nothing";
v = "restart";
}var age = 10, sex = 'm';
if (age > 18)
if (sex == 'm')
console.log('man');
else
console.log('kid');