Skip to main content

Command Palette

Search for a command to run...

Understanding Control Flow in JavaScript

Programs shouldn't always run in a straight line. Learn how to make your code make intelligent decisions using if, else, and switch statements.

Published
6 min read
H
CS Graduate | Technical Writing | Software development | 20K+ impressions

If you write a simple JavaScript program, the computer will read it exactly like a book: starting at line 1 and reading straight down to the bottom.

let userAge = 20;
console.log("Checking age...");
console.log("Welcome to the website.");

This top-to-bottom execution is fine for basic scripts, but it is useless for real applications. Real applications have to adapt. If a user enters the wrong password, you shouldn't log them in. If a shopping cart is empty, you shouldn't let the user click "Checkout."

We need a way to tell the computer: "If this specific condition is true, do this. If it is false, do something else."

In programming, this concept is called Control Flow. It allows you to break the straight line and create forks in the road. Instead of running every single line of code, the browser evaluates the current situation and decides which path to take.

Here is how we build those paths.


1. The if Statement: The Simple Fork

The most fundamental decision-making tool in JavaScript is the if statement. It checks a condition, and if that condition is exactly true, it runs a specific block of code. If it is false, it completely skips that block.

The structure looks like this:

  1. The keyword if

  2. A condition wrapped in parentheses ()

  3. A block of code wrapped in curly braces {}

let age = 15;

if (age >= 18) {
  // This code ONLY runs if the condition in the parentheses is true
  console.log("You are old enough to vote!");
}

console.log("End of program.");

Because 15 is not greater than or equal to 18, the condition is false. The computer completely ignores the console.log inside the curly braces. It jumps to the end and prints "End of program."

(Note: If you are wondering how >= works, refer to my previous guide on JavaScript Operators).


2. The if-else Statement: The Plan B

The if statement is great, but what if we want to give the user some feedback when they fail the check? We don't just want to skip the code in silence; we want to provide a fallback.

We do this by attaching an else block to the end of our if statement.

let age = 15;

if (age >= 18) {
  console.log("You are old enough to vote!");
} else {
  // This code runs if the first condition was false
  console.log("Sorry, you are too young to vote.");
}

Now, the code has a strict fork. It is mathematically impossible for both messages to print. The computer evaluates the condition, picks one of the two paths, executes it, and ignores the other.


3. The else if Ladder: Multiple Choices

Sometimes a simple "yes or no" isn't enough. You might have three, four, or five different possibilities. For example, assigning a letter grade based on a test score.

We can chain multiple conditions together using else if.

let score = 85;

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

How the computer reads this: The most important thing to know about an else if ladder is that it evaluates from top to bottom, and it stops at the very first true match.

In our example, score is 85.

  1. It checks score >= 90. (False). It moves on.

  2. It checks score >= 80. (True!). It prints "Grade: B".

  3. It immediately exits the ladder. It does not check score >= 70, even though 85 is technically greater than 70. Once it finds a true path, it ignores the rest of the chain.


4. The switch Statement: The Traffic Cop

The else if ladder is powerful, but it can get visually messy if you are checking the exact same variable against a long list of specific values.

Imagine you are building a calendar app, and you want to print the name of the day based on a number (1 = Monday, 2 = Tuesday, etc.). Writing else if (day === 1), else if (day === 2) seven times is tedious.

This is where the switch statement shines.

Instead of writing a condition for every single step, you hand the switch a single variable. It then checks that variable against a list of "cases."

let dayNumber = 3;

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

The Crucial Role of break

Notice the break keyword at the end of every case? This is vital.

When a switch statement finds a match (like case 3:), it starts executing the code. But unlike an if statement, a switch doesn't automatically stop when it's done. If you forget to write break;, the computer will "fall through" and execute case 4, case 5, and everything else below it, regardless of whether they match.

The break tells the computer: "We found our match. Stop checking and exit the switch."

The default keyword at the bottom acts exactly like an else. If none of the cases match, the default code runs.


Summary: if-else vs. switch

Beginners often ask: "When should I use if-else and when should I use switch?"

The rule of thumb is based on the type of question you are asking.

Use if-else when... Use switch when...
You are checking ranges (age > 18). You are checking for exact, single values (status === 'SUCCESS').
You have complex logic involving multiple variables (isAdult && hasTicket). You are evaluating one single variable against many possibilities.
You have 2 or 3 conditions. You have 4 or more exact matches (like error codes or days of the week).

Control flow is what breathes logic into your application. Without it, your code is just a static script. With it, your code can react to user input, handle errors gracefully, and make dynamic decisions on the fly.

If you feel shaky on the conditions inside the parentheses, make sure your foundation is solid by brushing up on JavaScript Operators. Once you understand how to compare data, controlling the flow becomes second nature.

1 views