JS: Conditional. 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");
}

Curly brackets {} optional

The curly brackets {} are optional when there is only one statement or expression in body.

if (3 < 4) console.log("yes");
// yes

If-Else Statement

if (3 <= 4) {
 console.log("yes");
} else {
 console.log("no");
}

// yes

Else-If Chain

const x = 3;
if (x == 1) {
 console.log("is 1");
} else if (x == 2) {
 console.log("is 2");
} else if (x == 3) {
 console.log("is 3");
} else {
 console.log("not found");
}
// is 3

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

JavaScript. Boolean