JavaScript If Else and Switch

JavaScript if else statements let your program make decisions: run one block of code when a condition is true and another when it is false. For many fixed choices, the switch statement is an alternative.

The if Statement

The code inside the braces runs only if the condition in parentheses is truthy.

const temperature = 31;
if (temperature > 30) {
  console.log("It's hot today");
}
It's hot today

if, else if and else

Chain conditions with else if. JavaScript checks them top to bottom and runs only the first block whose condition is true. else catches everything else.

const marks = 74;
let grade;
if (marks >= 90) {
  grade = "A";
} else if (marks >= 75) {
  grade = "B";
} else if (marks >= 60) {
  grade = "C";
} else {
  grade = "F";
}
console.log("Grade:", grade);
Grade: C

Truthy and Falsy Values

A condition does not need to be a boolean. JavaScript converts it. These values are falsy: false, 0, -0, 0n, "" (empty string), null, undefined and NaN. Everything else is truthy, including "0", [] and {}.

const values = [0, "", "0", [], null, "hi", NaN];
for (const v of values) {
  console.log(JSON.stringify(v), v ? "truthy" : "falsy");
}
0 falsy
"" falsy
"0" truthy
[] truthy
null falsy
"hi" truthy
null falsy

The switch Statement

switch compares one value against several cases using strict equality. Each case usually ends with break; without it, execution "falls through" into the next case. default runs when nothing matches.

const day = "sat";
switch (day) {
  case "sat":
  case "sun":
    console.log("Weekend");
    break;
  case "fri":
    console.log("Almost weekend");
    break;
  default:
    console.log("Weekday");
}
Weekend

Cleaner Alternatives

For simple value lookups, an object map is often shorter than switch, and the ternary operator handles two-way choices in a single expression.

const prices = { small: 3, medium: 4.5, large: 6 };
const size = "medium";
console.log(prices[size] ?? "Unknown size");

const isMember = true;
console.log(isMember ? "10% discount" : "No discount");
4.5
10% discount

Frequently asked questions

When should I use switch instead of if else?

Use switch when you compare one value against many fixed options. Use if else for ranges or combined conditions like marks >= 75 && attendance > 80.

What values are falsy in JavaScript?

false, 0, -0, 0n, empty string, null, undefined and NaN. Every other value, including empty arrays and objects, is truthy.

Does switch use == or ===?

switch uses strict equality (===), so case "1" will not match the number 1.