JS: if then else

By Xah Lee. Date: . Last updated: .

If Statement

Simple if-statement syntax:

if (testExpr) {body}

if (3 < 4) {
  console.log("yes");
  console.log("and yes");
}
if (3 < 4) {
  // something
  console.log("yes");
}

If-Else Statement

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"

JavaScript, Conditionals

BUY Ξ£JS JavaScript in Depth