Conditional Logic

Beginner · 18 min read · ▶ live playground · ✦ checkpoint

Your code can already ask questions. Now it needs to choose a path. JavaScript conditional logic lets your program decide which statements run with if, else if, else, and switch.

A conditional statement is a statement that runs one block of code only when a condition passes. A block is a group of statements wrapped in { }, a condition is the expression JavaScript tests for truthiness, and a branch is one possible path through the decision.

if chooses one path

An if statement runs a block only when its condition is truthy. It reads like a gate: if the condition passes, the block opens; if not, JavaScript walks past it.

const playerName = "Mina";
const score = 87;
let result = "";
 
if (score >= 70) {
  result = "passed";
}
 
console.log(`${playerName} ${result}.`);

Mina passed.

Most conditions should be direct comparisons or logical expressions. You can write if (score), because every value has truthiness now, but if (score >= 70) says the real question out loud.

When there are several possible paths, add else if, which checks another condition after the first one fails, and else, which runs when none of the earlier conditions pass. An else-if chain is a top-to-bottom list of conditions where the first passing branch wins.

const playerName = "Mina";
const score = 87;
let badge = "";
 
if (score >= 90) {
  badge = "gold";
} else if (score >= 70) {
  badge = "silver";
} else if (score >= 50) {
  badge = "practice pass";
} else {
  badge = "retry ticket";
}
 
console.log(`${playerName} earns: ${badge}`);

Mina earns: silver. JavaScript stops at the first true branch, so the later branches do not run.

The order matters. If you put score >= 50 before score >= 90, a score of 95 would match the weaker question first and never reach the gold branch. Write the most specific checks first.

Try it — keep the main path flat

Read this from top to bottom before you run it. The first branches handle problems. The final else is the normal path.

javascript — live consolereal engine
⌘/Ctrl + Enter to run

This is the habit you want: clear checks, one final happy path, no maze of braces. Try changing hasBadge to false, then try setting requestedRoom to "".

Flat beats nested

Nested code is code placed inside another block. A little nesting is normal. Too much nesting makes the reader hold several unfinished questions in their head at once.

const username = "";
const credits = 3;
let accessMessage = "";
 
if (username !== "") {
  if (credits > 0) {
    accessMessage = `${username} can start the lesson.`;
  } else {
    accessMessage = "Add a credit before starting.";
  }
} else {
  accessMessage = "Choose a username first.";
}
 
console.log(accessMessage);

Choose a username first.

A guard clause is an early check for a case that would make the main path wrong or impossible. Think of it like checking for a locked door before you carry furniture down the hallway. Handle the blocker first; keep the normal path easy to see.

const username = "";
const credits = 3;
let accessMessage = "";
 
if (username === "") {
  accessMessage = "Choose a username first.";
} else if (credits <= 0) {
  accessMessage = "Add a credit before starting.";
} else {
  accessMessage = `${username} can start the lesson.`;
}
 
console.log(accessMessage);

Choose a username first. Same behavior, less mental bookkeeping.

You'll later meet early returns, the function version of this idea: leave a reusable block of code as soon as a guard fails. Functions and return start in Section 5, so for now the pattern is "check the exceptional case first, then let the normal path stay flat."

switch chooses by matching one value

A switch statement compares one chosen value against labeled cases, like sending one ticket code to the matching counter. A case is one possible matching label, and default is the branch for "nothing matched."

const mood = "focused";
let playlist = "";
 
switch (mood) {
  case "tired":
    playlist = "quiet piano";
    break;
  case "focused":
    playlist = "lo-fi beats";
    break;
  case "celebrating":
    playlist = "dance mix";
    break;
  default:
    playlist = "daily mix";
}
 
console.log(`Play: ${playlist}`);

Play: lo-fi beats.

switch uses strict matching, the same spirit as ===: "5" does not match 5. The break statement exits the switch immediately. Without it, JavaScript keeps going.

Fall-through is powerful and dangerous

Fall-through means execution continues into the next case after a match because no break stopped it. Picture water moving down steps until it hits a closed gate.

const badge = "gold";
let perks = "Perks:";
 
switch (badge) {
  case "gold":
    perks = `${perks} lounge`;
  case "silver":
    perks = `${perks}, priority support`;
  case "bronze":
    perks = `${perks}, newsletter`;
    break;
  default:
    perks = `${perks} none`;
}
 
console.log(perks);

Perks: lounge, priority support, newsletter. A gold badge intentionally receives the silver and bronze perks too.

Most missing break statements are bugs. Intentional fall-through is useful only when the lower cases really should run too. If that is your plan, leave a short comment in real code so the next reader knows you meant it.

When switch gets too long

switch is good when each case has a few statements or special behavior. It gets noisy when all you are doing is mapping one known code to one known value, like "basic" to "Basic plan" or "pro" to "Pro plan".

A lookup object is an object whose keys act like labels you can read by name. You have not learned object literals yet, so do not reach for this pattern today. In Section 7, you'll learn how objects let you replace long value-mapping switches with data instead of more branches.

For now, use if when the questions are different, use switch when one value is being matched against several labels, and keep the main path visible.

You can choose one path now. Next, loops teach your program to repeat a path until a job is finished.

Checkpoint

Answer all three to mark this lesson complete

+50 XP on completion