JavaScript Conditional Statements

Conditional statements let your code make decisions: run a block only if a condition is true, pick one of many paths, or choose a quick inline result.

1) if Statement

Runs a block when the condition is true.


let age = 20;
if (age >= 18) {
  console.log("You can vote");
}

2) if...else

Adds an alternative block when the condition is false.


if (age >= 18) {
  console.log("Adult");
} else {
  console.log("Minor");
}

3) else if Ladder

Test multiple conditions in order; the first match runs.


let score = 75;
if (score >= 90) {
  console.log("Grade A");
} else if (score >= 60) {
  console.log("Grade B");
} else {
  console.log("Grade C");
}

4) Nested if

Place an if inside another for combined checks.


let num = 15;
if (num > 0) {
  if (num % 2 === 0) {
    console.log("Positive Even");
  } else {
    console.log("Positive Odd");
  }
}

5) switch Statement

Select one code path based on the value. Remember to use break to avoid fall-through.


let day = 3;
switch (day) {
  case 1: console.log("Monday"); break;
  case 2: console.log("Tuesday"); break;
  case 3: console.log("Wednesday"); break;
  default: console.log("Other day");
}

6) Ternary Operator

Short inline choice: condition ? valueIfTrue : valueIfFalse.


let age = 20;
let msg = (age >= 18) ? "Adult" : "Minor";
console.log(msg);
Tip: Use switch when you compare the same variable to many values; use if / else if for ranges like score >= 90.