JavaScript if/else Statements: A Beginner’s Guide

If/else statements let JavaScript make decisions, running different code depending on whether a condition is true or false. This guide covers if, else, and else if, step by step, along with the comparisons that make conditions actually work.

If you’ve worked through our guides on variables and functions, you’re ready for the piece that makes programs genuinely responsive: the ability to check a condition and act differently depending on the answer.

The Basic if Statement

An if statement runs a block of code only when a specific condition is true. According to MDN’s guide to conditionals, JavaScript’s code needs to make decisions and carry out actions depending on different inputs — an if statement is the most common way to express that logic.

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

Here, age >= 18 is the condition. If it evaluates to true, the code inside the curly braces runs. If it’s false, JavaScript simply skips that block and moves on — nothing prints, and no error occurs.

Adding an else for the Opposite Case

Often you want something to happen in both cases — one outcome if the condition is true, a different one if it’s false. That’s what else provides:

let age = 15;
if (age >= 18) {
  console.log("You are eligible to vote.");
} else {
  console.log("You are not old enough to vote yet.");
}

According to W3Schools’ guide to if/else statements, use else to specify a block of code to be executed if the same condition is false — acting as a fallback that runs whenever the condition above it doesn’t hold.

Chaining Conditions With else if

Sometimes two options aren’t enough — you need to check several possibilities in sequence. That’s what else if is for:

let score = 85;
let grade;

if (score >= 90) {
  grade = "A";
} else if (score >= 80) {
  grade = "B";
} else if (score >= 70) {
  grade = "C";
} else {
  grade = "F";
}

console.log(`Your grade is: ${grade}`);

As freeCodeCamp’s guide to if statements explains, JavaScript checks each condition in order and stops at the first one that’s true — the remaining else if and else blocks are skipped entirely once a match is found, even if a later condition would also technically be true. Note there’s no single “elseif” keyword in JavaScript — it’s always written as two separate words, else if.

The Comparison Operators You’ll Use Constantly

Conditions rely on comparison operators to produce a true or false result:

  • === — strictly equal to (checks both value and type, the recommended default)
  • !== — strictly not equal to
  • > and < — greater than / less than
  • >= and <= — greater than or equal to / less than or equal to

JavaScript also has a looser == operator, which compares values without checking type, occasionally producing surprising results (like "5" == 5 being true). Using === by default avoids this category of confusing bug entirely, and is the widely recommended modern default.

Truthy and Falsy Values

JavaScript conditions don’t only work with explicit true and false — many other values are automatically treated as true or false when used in a condition. According to MDN’s reference, values like 0, an empty string "", null, undefined, and NaN are all treated as “falsy,” while most other values are “truthy”:

let name = "";
if (name) {
  console.log(`Hello, ${name}!`);
} else {
  console.log("No name provided.");
}

Here, an empty string is falsy, so the else branch runs. This pattern — checking a variable directly rather than comparing it explicitly to an empty value — is extremely common in real JavaScript code.

Combining Conditions With && and ||

Sometimes a decision depends on more than one condition at once. JavaScript’s && (AND) and || (OR) operators let you combine them:

let age = 25;
let hasLicense = true;

if (age >= 18 && hasLicense) {
  console.log("Eligible to drive.");
} else {
  console.log("Not eligible to drive.");
}

&& requires both conditions to be true; || requires only one of them to be true. Understanding which one your logic actually needs is a common source of subtle bugs when first combining conditions.

The Ternary Operator: A Shorter Alternative

For simple cases where you’re just choosing between two values, JavaScript offers a compact, single-line alternative called the ternary operator:

let age = 20;
let status = age >= 18 ? "adult" : "minor";
console.log(status);

This is functionally identical to a full if/else block that assigns a value to status, just written on one line. It’s worth knowing this form exists since you’ll see it constantly in real-world code, but a full if/else block is usually clearer while you’re still learning — reach for the ternary shorthand once the basic pattern feels completely natural.

When to Reach for a switch Statement Instead

Once you have several else if conditions all checking the exact same variable against different fixed values, a switch statement is often cleaner to read:

let day = "Wednesday";

switch (day) {
  case "Monday":
    console.log("Start of the week.");
    break;
  case "Wednesday":
    console.log("Midweek.");
    break;
  case "Friday":
    console.log("Almost the weekend.");
    break;
  default:
    console.log("Just another day.");
}

Each case checks the switch value against a specific match, and break stops execution once a match is found — forgetting break is a common beginner mistake, since without it JavaScript will keep running the following cases regardless of whether they match. A switch is best reserved for exactly this pattern: many fixed values compared against one variable. For conditions involving ranges, comparisons, or multiple different variables, if/else remains the clearer choice.

A Practical Example Combining Everything

Here’s a slightly larger example tying together conditions with the arrays and loops covered earlier in this series:

const numbers = [3, -1, 0, 8, -5];

for (const num of numbers) {
  if (num > 0) {
    console.log(`${num} is positive`);
  } else if (num < 0) {
    console.log(`${num} is negative`);
  } else {
    console.log(`${num} is zero`);
  }
}

This loops through an array and, for each number, checks whether it's positive, negative, or exactly zero — a genuinely common pattern combining loops and conditions together, and one you'll reuse constantly once it feels natural.

Common Mistakes Beginners Make With Conditions

One of the most frequent early mistakes is using a single equals sign (=) instead of a comparison operator inside a condition — if (x = 10) assigns 10 to x rather than comparing it, and since the assignment itself evaluates as truthy, the condition silently passes every time regardless of what x was before. JavaScript won't stop you from writing this, unlike some languages, which is exactly why it's worth double-checking your comparison operators carefully, especially inside conditions you're debugging.

Another common mistake is writing overly complex OR conditions incorrectly, like assuming if (x === 5 || 7) checks whether x equals 5 or 7. It doesn't — it actually checks whether x === 5 is true, or whether the number 7 by itself is truthy (which it always is), meaning the condition is always true regardless of x. The correct version repeats the full comparison on both sides: if (x === 5 || x === 7).

Common Questions Beginners Ask About If/Else

Do I always need an else? No. An if statement without an else is completely valid — it simply does nothing when the condition is false.

What's the difference between == and ===? == compares values loosely, converting types if needed; === compares strictly, requiring both value and type to match. Using === by default avoids a whole category of confusing, hard-to-trace bugs.

Can I nest if statements inside each other? Yes — an if statement can contain another if statement inside its block. This is valid and sometimes necessary, but deeply nested conditions can get hard to read, so it's often worth combining conditions with && instead once nesting gets more than two or three levels deep.

Quick-Reference JavaScript If/Else Guide

  • if (condition) { } — runs the block only if the condition is true.
  • else { } — a fallback that runs when the if condition is false.
  • else if (condition) { } — checks an additional condition if the earlier ones were false.
  • === vs == — strict equality checks type; loose equality can produce surprises.
  • && / || — combine multiple conditions into one check.
  • Ternary operator — a compact one-line alternative for simple if/else logic.

Conclusion

If/else statements are what let a JavaScript program actually respond to different situations, rather than running the same fixed sequence of steps every time. Understanding the basic if, adding else for the opposite case, and chaining additional conditions with else if covers the overwhelming majority of decision-making logic you'll write as a beginner.

The best way to build comfort here is direct practice: write a few small conditions yourself, checking things like whether a number is even, whether a password meets a minimum length, or whether a value falls within a range.

In the next guide in this series, we'll cover JavaScript loops in more depth — how for and while loops differ, and when to reach for each one.

Explore More JavaScript Basics Guides →

Leave a Comment

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

Scroll to Top