JS: if then else
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 automatically converted to true/false (boolean) 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.((4 > 5) ? "yes" : "no") === "no"