🌱BeginnerControl Flow

Conditionals

if/else, switch, and the ternary operator making decisions in code.

Overview

Conditionals let your program make decisions based on data. The most fundamental conditional in JavaScript is the if statement: evaluate an expression, and if it is truthy, run the block. An optional else branch runs when the condition is false. JavaScript's truthiness/falsiness rules determine what counts as "truthy". Six values are falsy: false, 0, "" (empty string), null, undefined, and NaN. Everything else including empty arrays [], empty objects {}, and the string "false" is truthy. This leads to very concise conditionals but also surprises when you forget that 0 is falsy. The switch statement is syntactic sugar for chaining multiple equality checks against a single value. It's cleaner than a long if/else if chain when you have many discrete cases. The ternary operator (condition ? trueVal : falseVal) is a one-line conditional expression useful for simple inline decisions.

Key Points

  • •Six falsy values: false, 0, "", null, undefined, NaN everything else is truthy
  • •else if lets you chain multiple conditions; only the first truthy branch runs
  • •switch uses strict equality (===) to match cases always include break to avoid fall-through
  • •Ternary operator: condition ? valueIfTrue : valueIfFalse best for simple, single-expression choices
  • •if (value) is a common short-hand to check whether a value is truthy (non-null, non-empty, non-zero)
  • •Nested conditionals can usually be simplified with early returns or logical operators

Examples

if / else if / else

const score = 75;

if (score >= 90) {
  console.log("A");
} else if (score >= 80) {
  console.log("B");
} else if (score >= 70) {
  console.log("C");
} else {
  console.log("F");
}
// Output: "C"

switch matching a specific value

const day = "Monday";

switch (day) {
  case "Monday":
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
  case "Friday":
    console.log("Weekday");
    break;
  case "Saturday":
  case "Sunday":
    console.log("Weekend");
    break;
  default:
    console.log("Unknown");
}

Without break, execution falls through to the next case. Stacking cases (no break between them) intentionally shares logic.

Ternary operator

const age = 20;
const access = age >= 18 ? "allowed" : "denied";
console.log(access); // "allowed"

// Equivalent if/else:
// let access;
// if (age >= 18) { access = "allowed"; } else { access = "denied"; }

Common Mistakes

  • Forgetting break in a switch case causing "fall-through" where multiple cases run
  • Using a single = (assignment) instead of === inside an if condition
  • Not accounting for falsy 0 when checking for numeric values: if (count) misses the case where count is 0

Exercises

Write JavaScript code to solve each exercise. Run it and check your output.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

Which of these values is truthy in JavaScript?