JavaScript: Branch Control: if then else, switch
If Statement
Simple if-statement syntax:
if (testExpr) {body}
The curly brackets {} are optional when there is only one statement or expression in body.
If testExpr is true, run body, else do nothing.
The testExpr is forced into one of true or false by Boolean Constructor.
if (3 < 4) { console.log("yes"); console.log("and yes"); }
if (3 < 4) { // something console.log("yes"); }
If-Else Statement
if (testExpr) {trueBody} else {falseBody}
if (3 <= 4) { // something console.log("yes"); } else { // something console.log("no"); }
Else-If Chain
const x = 3; if (x == 1) { // something console.log("is 1"); } else if (x == 2) { // something console.log("is 2"); } else if (x == 3) { // something console.log("is 3"); } else { // something console.log("not found"); }
If-Then-Else Expression
testExpr ? expr1 : expr2
-
if testExpr eval to
true
, then return expression expr1, else return expr2.console.log(((4 > 5) ? "yes" : "no") === "no");
Switch Statement
The switch statement compares a value to a sequence of values, one by one.
Tip: switch is not useful. It is not a replacement for if-else chain, because it only compares a value, you cannot give it a general true/false expression.
Switch-statement uses the Triple Equal Operator to test equality.
// example of switch statement const x = "a"; switch (x) { case "w": console.log("is w"); break; // without break, it'll continue to run rest without testing case "a": console.log("is a"); break; case 3: console.log("is 3"); break; default: console.log("none of the above"); }
Warning: JavaScript Switch-Statement is Goto
JavaScript's switch-statement does fall-through. It'll jump to a matching point and run all of the rest of case code without testing. Think of JavaScript switch as goto.
Add
break
if you want it to exit.