Reading history

JavaScript if, else and switch Statements (With Examples)

4 min read 0 views

Learn JavaScript conditions: if, else if and else, switch with break, and the full list of truthy and falsy values.

Programs need to make decisions: show an error if a password is too short, give a discount on large orders, greet the user differently in the morning. JavaScript makes these decisions with if, else if, else and switch. To use them well you also need to know which values JavaScript treats as true and which as false, because conditions do not have to be real booleans.

In this lesson you will learn

  • How if, else if and else choose a path
  • How switch compares one value against many cases
  • Why break or return matters in a switch
  • Truthy and falsy values

if, else if and else

function grade(marks) {
  if (marks >= 80) {
    return "A+";
  } else if (marks >= 70) {
    return "A";
  } else if (marks >= 60) {
    return "A-";
  } else if (marks >= 40) {
    return "Pass";
  } else {
    return "Fail";
  }
}

for (const m of [91, 74, 63, 45, 22]) {
  console.log(m, "->", grade(m));
}

Output

91 -> A+
74 -> A
63 -> A-
45 -> Pass
22 -> Fail
  • The condition goes in parentheses. If it is true, the block in braces runs and the rest of the chain is skipped.
  • Conditions are checked from top to bottom, so order matters. Because 91 passes the first test, it never reaches the later ones. If marks >= 40 came first, every passing mark would be graded “Pass”.
  • else has no condition. It catches everything not matched above it.
  • Returning from inside each branch, as grade() does, is a common and readable pattern.

switch and Truthy/Falsy Values

function dayType(day) {
  switch (day) {
    case "Friday":
    case "Saturday":
      return "Weekend";
    case "Sunday":
    case "Monday":
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
      return "Workday";
    default:
      return "Unknown day";
  }
}
console.log(dayType("Friday"), dayType("Monday"), dayType("Funday"));

const samples = [
  ["0", 0], ['""', ""], ["null", null], ["undefined", undefined],
  ["NaN", NaN], ["false", false], ['"0"', "0"], ['" "', " "],
  ["[]", []], ["{}", {}], ["-1", -1],
];
for (const [label, value] of samples) {
  console.log(label.padEnd(9), value ? "truthy" : "falsy");
}

Output

Weekend Workday Unknown day
0         falsy
""        falsy
null      falsy
undefined falsy
NaN       falsy
false     falsy
"0"       truthy
" "       truthy
[]        truthy
{}        truthy
-1        truthy
  • switch compares one value with each case using strict equality (===).
  • Stacking cases with no code between them, as with Friday and Saturday, lets several values share one result.
  • When a case matches, execution continues downwards until a break or return. Forgetting break causes “fall-through” into the next case. Here each case returns, so no break is needed.
  • default runs when no case matches.

In a condition, any value is accepted. Exactly these values count as falsy: false, 0, -0, 0n, "", null, undefined and NaN. Everything else is truthy, including "0", a string with a space, empty arrays and empty objects. That lets you write if (name) { ... } to check that a string is not empty.

if/else, switch or Ternary?

UseWhen
if / else if / elseRanges and mixed conditions, such as marks bands
switchOne value compared against many fixed options
cond ? a : bChoosing between two values in a single expression

Common Mistakes

  1. Wrong order of conditions, so a general test catches values meant for a specific one.
  2. Missing break in a switch, running the next case by accident.
  3. Expecting an empty array to be falsy. Check arr.length === 0 instead.
  4. Writing if (x == 1 || 2); the 2 on its own is always truthy. Write x === 1 || x === 2.

Practice Exercises

Exercise 1. Print “Good morning” before 12, “Good afternoon” before 18, otherwise “Good evening”, using new Date().getHours().

Show answer
const hour = new Date().getHours();
if (hour < 12) {
  console.log("Good morning");
} else if (hour < 18) {
  console.log("Good afternoon");
} else {
  console.log("Good evening");
}

Exercise 2. Write a switch that turns 1, 2 and 3 into “Gold”, “Silver” and “Bronze”, and anything else into “No medal”.

Show answer
function medal(place) {
  switch (place) {
    case 1: return "Gold";
    case 2: return "Silver";
    case 3: return "Bronze";
    default: return "No medal";
  }
}

Frequently Asked Questions

Can I leave out the braces for a one-line if?

Yes, if (ok) run(); is valid, but adding a second line later without braces is a classic bug. Most style guides recommend always using braces.

Does switch work with strings?

Yes. It compares with ===, so it works with strings, numbers and any other values. The match is case-sensitive.

Summary

  • if / else if / else run the first branch whose condition is true.
  • switch matches one value against cases with ===; end cases with break or return.
  • Only eight values are falsy; everything else, including [] and "0", is truthy.

Next: JavaScript Loops.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *