JavaScript Conditionals: If, Else & Switch

Master the art of decision-making in your code by learning how to control its flow with conditional logic.

Lesson ProgressStep 1 of 9
let age = 20;if (age > 18) { console.log("Adult");}else { console.log("Minor");}
0 EXP

Hello! Let's explore how JavaScript makes decisions. This is called 'control flow'.

// Welcome to the Logic Simulator

The `if` Statement

The `if` statement is the most fundamental conditional. It executes a block of code only if its condition is **true**.

A condition is an expression that evaluates to `true` or `false`. We create them using **comparison operators**:

  • === (Strictly equals)
  • !== (Strictly not equals)
  • > (Greater than)
  • <= (Less than or equal to)
let age = 20;

if (age > 18) {
  console.log("You are an adult.");
}

System Check

Which operator checks for both equal value AND equal type?

Advanced Holo-Simulations

0 EXP

Log in to unlock these advanced training modules and test your skills.


Achievements

🏆
Logic Starter

Write a correct `if` statement.

⛓️
Logic Chain

Build a full `if-else if-else` chain.

🕹️
Switch Expert

Correctly use a `switch` statement with `break`.

Mission: The Grading System

Write an `if-else if-else` chain. If `score` is 90+, log "A". If 80+, log "B". Otherwise, log "C". Our AI assistant will provide real-time feedback.

A.D.A. Feedback:

> System integrity looks stable. Code is valid.

Challenge: Order the `switch`

Drag the elements into the correct order to build a valid `switch` statement.

case 'a':
default:
switch (value) {
}
break;

Challenge: Complete the Logic Chain

Fill in the missing keywords to check a user's status.

(user.role === "admin") {
  console.log("Admin access");
} (user.role === "editor") {
  console.log("Editor access");
} {
  console.log("Guest access");
}

Consult A.D.A.

Community Holo-Net

Mastering Control Flow: A Deep Dive into JavaScript Conditionals

At its core, programming is about making decisions. **Control Flow** is the order in which the computer executes statements in a script. By default, code runs from top to bottom. However, JavaScript provides powerful tools called **conditional statements** that allow you to disrupt this flow, execute different blocks of code based on specific conditions, and create dynamic, responsive applications.

Mastering these tools is the difference between a static page and a fully interactive web application.

1. The `if` Statement: The Foundational Decision

The `if` statement is the simplest conditional. It executes a block of code **only if** a specified condition evaluates to `true`.

let temperature = 30;

if (temperature > 25) {
  console.log("It's a hot day!");
}
// Output: It's a hot day!

If `temperature` was 20, the condition `(20 > 25)` would be `false`, and the code inside the `` block would be skipped entirely.

2. The `if...else` Statement: The "Otherwise" Path

An `if` statement is often paired with an `else` statement to provide a fallback. If the `if` condition is `false`, the `else` block is executed. This handles the "otherwise" scenario.

let isLoggedIn = false;

if (isLoggedIn === true) {
  console.log("Welcome back, user!");
} else {
  console.log("Please log in.");
}
// Output: Please log in.

3. The `if...else if...else` Ladder

When you have more than two possibilities, you can chain multiple conditions together using `else if`. JavaScript will check each condition from top to bottom and execute the *first* block that evaluates to `true`. If none are true, the final `else` block runs.

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");
}
// Output: Grade: B

4. The `switch` Statement: The Clean Alternative

When you have a long `if...else if` chain that checks a *single variable* against multiple *specific values*, a `switch` statement is often cleaner and more readable.

  • It evaluates an expression (e.g., `dayOfWeek`).
  • It matches the expression's value to a `case` clause.
  • The `break` keyword is essential. It stops execution and exits the `switch` block. Without it, the code would "fall through" and execute the next `case` as well!
  • The `default` clause is a fallback, similar to `else`, if no `case` matches.
let dayOfWeek = "Wednesday";

switch (dayOfWeek) {
  case "Monday":
    console.log("Start of the week.");
    break;
  case "Wednesday":
    console.log("Hump day!");
    break;
  case "Friday":
    console.log("Weekend is here!");
    break;
  default:
    console.log("It's some other day.");
}
// Output: Hump day!

5. The Ternary Operator: The One-Liner Conditional

The conditional (or "ternary") operator is a compact shortcut for a simple `if...else` statement. It's often used to assign a value to a variable based on a condition.

Syntax: condition ? expressionIfTrue : expressionIfFalse

let age = 21;
let message = (age >= 18) ? "Can vote" : "Cannot vote";

console.log(message);
// Output: Can vote

6. Truthy and Falsy Values: The Hidden Conditions

In JavaScript, conditions don't have to be strictly `true` or `false`. Any value can be evaluated in a conditional context. JavaScript has six **falsy** values—values that are treated as `false` in a conditional:

  • `false`
  • `0` (zero)
  • `""` (an empty string)
  • `null`
  • `undefined`
  • `NaN` (Not a Number)

**Everything else is truthy.** This includes non-empty strings (`"hello"` , `"0"`), non-zero numbers (`-1`, `100`), objects (``), and arrays (`[]`). This allows for powerful shortcuts:

let username = "";

if (username) { // This is falsy
  console.log("Welcome, " + username);
} else {
  console.log("Please enter a username.");
}
// Output: Please enter a username.
Key Takeaway: Always use the **strict equality operator (`===`)** instead of the loose equality operator (`==`). `===` checks both value and type, preventing bugs where `0 == false` evaluates to `true`.

JavaScript Conditionals Glossary

Condition
An expression that evaluates to a Boolean value (`true` or `false`). Example: `age > 18`.
`if`
The keyword that begins a conditional block. The code inside its `` runs only if the condition is `true`.
`else`
A keyword for a fallback block. The code inside its `` runs if all preceding `if` and `else if` conditions are `false`.
`else if`
A keyword to chain multiple conditions. It provides a new condition to test if the previous one was `false`.
`switch`
A statement that evaluates a single expression and matches its value against a series of `case` clauses.
`case`
A keyword inside a `switch` block that defines a specific value to match.
`break`
A keyword that exits the current `switch` block (or loop). It prevents "fall-through" to the next `case`.
`default`
A keyword inside a `switch` block that specifies the code to run if no `case` matches.
Ternary Operator (`? :`)
A one-line shortcut for an `if...else` statement. Syntax: `condition ? valueIfTrue : valueIfFalse`.
Truthy
A value that is considered `true` when evaluated in a Boolean context. Examples: `"hello"`, `1`, `[]`, ``.
Falsy
A value that is considered `false` when evaluated in a Boolean context. The six falsy values are: `false`, `0`, `""`, `null`, `undefined`, and `NaN`.
`===` (Strict Equality)
Checks if two values are equal in both **value** and **type**. Almost always preferred. Example: `5 === 5` (true), `5 === "5"` (false).
`==` (Loose Equality)
Checks if two values are equal after performing **type coercion** (converting types). Can lead to bugs. Example: `5 == "5"` (true).

About the Author

Author's Avatar

TodoTutorial Team

Passionate developers and educators making programming accessible to everyone.

This article was written and reviewed by our team of web development experts, who have years of experience teaching JavaScript and building robust web applications.

Verification and Updates

Last reviewed: November 2025.

We strive to keep our content accurate and up-to-date. This tutorial is based on the latest ECMAScript specifications and is periodically reviewed to reflect industry best practices.

External Resources

Found an error or have a suggestion? Contact us!