JavaScript if else: How Conditional Statements Work

JavaScript if else statements let your code make decisions.

A shopping website can show an out-of-stock message when quantity reaches zero. A login page can show one message for a correct password and another for an incorrect one. A form can check whether required information is missing.

JavaScript uses if, else if, and else to decide which block of code should run.

Course Home: JavaScript Tutorial for Beginners
Previous Lesson: JavaScript Logical Operators Explained
Next Lesson: JavaScript switch Statement Explained

Quick Answer

A JavaScript if statement runs code when a condition is truthy.

const age = 20;

if (age >= 18) {
    console.log("Adult");
}

Output:

Adult

Use else when you want another block to run if the condition fails:

const age = 16;

if (age >= 18) {
    console.log("Adult");
} else {
    console.log("Under 18");
}

Output:

Under 18

Use else if when you need to test another condition:

const score = 75;

if (score >= 90) {
    console.log("Excellent");
} else if (score >= 60) {
    console.log("Pass");
} else {
    console.log("Try again");
}

What Is an if Statement in JavaScript?

An if statement checks a condition.

If that condition is truthy, JavaScript runs the code inside the block.

The basic syntax is:

if (condition) {
    // code runs when condition is truthy
}

Example:

const stock = 5;

if (stock > 0) {
    console.log("In stock");
}

Output:

In stock

The condition is:

stock > 0

That comparison returns:

true

so JavaScript runs the code inside the braces.

If comparison operators are still unclear, review the JavaScript Comparison Operators tutorial.

Why if else Is Important

Most useful websites need to make decisions.

For example:

  • Show a login button when the user is logged out.
  • Show free shipping when the cart reaches a minimum amount.
  • Show an error when a form field is empty.
  • Allow checkout only when a product is in stock.
  • Show one price for members and another for guests.
  • Display one message for mobile users and another for desktop users.
  • Check whether a user is an admin, editor, or customer.

Without conditional statements, your JavaScript would run the same code every time.

if else lets the program respond to different values and situations.

JavaScript if Syntax

The basic structure is:

if (condition) {
    // code
}

For example:

const temperature = 35;

if (temperature > 30) {
    console.log("It is hot");
}

Output:

It is hot

The code inside the braces runs only when the condition passes.

What Happens When the Condition Is False?

Consider:

const temperature = 20;

if (temperature > 30) {
    console.log("It is hot");
}

Nothing is printed.

Why?

This condition:

temperature > 30

returns:

false

Because the condition fails, JavaScript skips the block.

JavaScript else Statement

Use else when you want another block to run when the if condition is falsy.

Syntax:

if (condition) {
    // runs when condition passes
} else {
    // runs when condition fails
}

Example:

const age = 16;

if (age >= 18) {
    console.log("Adult");
} else {
    console.log("Under 18");
}

Output:

Under 18

Only one block runs.

Real Website Example: Product Stock

Suppose:

const stock = 0;

You can show different messages:

if (stock > 0) {
    console.log("Product available");
} else {
    console.log("Out of stock");
}

Output:

Out of stock

This is one of the simplest real uses of if else.

JavaScript else if

Use else if when you need more than two possible outcomes.

Syntax:

if (condition1) {
    // first result
} else if (condition2) {
    // second result
} else {
    // fallback result
}

Example:

const score = 75;

if (score >= 90) {
    console.log("Excellent");
} else if (score >= 60) {
    console.log("Pass");
} else {
    console.log("Try again");
}

Output:

Pass

JavaScript checks the conditions from top to bottom.

The first matching branch runs.

After that, the rest of the chain is skipped.

How JavaScript Checks an if else Chain

Consider:

const score = 95;

if (score >= 90) {
    console.log("Excellent");
} else if (score >= 60) {
    console.log("Pass");
} else {
    console.log("Try again");
}

The first condition:

score >= 90

is true.

JavaScript prints:

Excellent

It does not continue to the next else if.

This matters when several conditions could be true at the same time.

Put More Specific Conditions First

Suppose:

const score = 95;

This order works:

if (score >= 90) {
    console.log("Excellent");
} else if (score >= 60) {
    console.log("Pass");
}

But this order is wrong for the intended result:

if (score >= 60) {
    console.log("Pass");
} else if (score >= 90) {
    console.log("Excellent");
}

A score of 95 already satisfies:

score >= 60

so JavaScript prints:

Pass

The score >= 90 branch is never reached.

When conditions overlap, put the more specific check first.

Real Website Example: Shipping Cost

Suppose a store has these rules:

  • Free shipping for carts of ₹2,000 or more.
  • ₹100 shipping for carts of ₹1,000 or more.
  • ₹200 shipping for smaller carts.
const cartTotal = 1500;

let shipping;

if (cartTotal >= 2000) {
    shipping = 0;
} else if (cartTotal >= 1000) {
    shipping = 100;
} else {
    shipping = 200;
}

console.log(shipping);

Output:

100

The rules are checked from highest cart value to lowest.

Using Comparison Operators Inside if

Most conditions use comparison operators.

For example:

const quantity = 3;

if (quantity > 0) {
    console.log("Available");
}

You can use:

===
!==
>
<
>=
<=

Example:

const role = "admin";

if (role === "admin") {
    console.log("Open admin dashboard");
}

Strict equality makes the comparison clear.

Using Logical Operators Inside if

You can combine conditions with logical operators.

Example:

const age = 22;
const hasTicket = true;

if (age >= 18 && hasTicket) {
    console.log("Entry allowed");
}

The condition passes only when both checks pass.

You can also use OR:

const isAdmin = false;
const isEditor = true;

if (isAdmin || isEditor) {
    console.log("Editing allowed");
}

And NOT:

const blocked = false;

if (!blocked) {
    console.log("Access allowed");
}

Review the JavaScript Logical Operators tutorial if you need more practice with &&, ||, and !.

Real Website Example: Login Check

Suppose:

const emailCorrect = true;
const passwordCorrect = true;

You can check both:

if (emailCorrect && passwordCorrect) {
    console.log("Login successful");
} else {
    console.log("Email or password is incorrect");
}

Output:

Login successful

If either value becomes false, the else block runs.

Real Website Example: Free Shipping

Suppose free shipping applies when:

  • The cart total is at least ₹1,000
  • Or the customer is a premium member
const cartTotal = 700;
const premiumMember = true;

if (cartTotal >= 1000 || premiumMember) {
    console.log("Free shipping");
} else {
    console.log("Shipping charge applies");
}

Output:

Free shipping

Only one of the two conditions needs to pass.

Conditions Can Use Boolean Variables Directly

Suppose:

const loggedIn = true;

You do not need:

if (loggedIn === true) {
    console.log("Welcome");
}

You can write:

if (loggedIn) {
    console.log("Welcome");
}

This is clear because loggedIn already contains a boolean.

For the opposite check:

if (!loggedIn) {
    console.log("Please log in");
}

Truthy and Falsy Values in if Statements

An if statement does not require a literal true or false.

JavaScript checks the truthiness of the condition.

For example:

const name = "Amit";

if (name) {
    console.log("Name entered");
}

Output:

Name entered

The string is non-empty, so it is truthy.

Now:

const name = "";

if (name) {
    console.log("Name entered");
}

Nothing is printed because an empty string is falsy.

Common falsy values include:

false
0
-0
0n
""
null
undefined
NaN

You learned these in the JavaScript Logical Operators lesson.

Real Website Example: Required Form Field

Suppose:

const email = "";

You can check it:

if (!email) {
    console.log("Email is required");
}

Output:

Email is required

Because an empty string is falsy, !email becomes true.

Multiple else if Conditions

You can use more than one else if.

Example:

const score = 82;

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

Output:

Grade B

JavaScript checks each condition in order until one passes.

Real Website Example: Product Discount

Suppose a store gives different discounts.

const cartTotal = 6000;

let discount;

if (cartTotal >= 10000) {
    discount = 20;
} else if (cartTotal >= 5000) {
    discount = 10;
} else if (cartTotal >= 2000) {
    discount = 5;
} else {
    discount = 0;
}

console.log(`${discount}% discount`);

Output:

10% discount

Again, the largest threshold appears first.

Nested if Statements

An if statement can appear inside another if.

This is called a nested if statement.

Example:

const loggedIn = true;
const role = "admin";

if (loggedIn) {
    if (role === "admin") {
        console.log("Admin dashboard");
    }
}

Output:

Admin dashboard

The inner condition is checked only if the outer condition passes.

When Nested if Can Help

Nested checks can be useful when the second condition only matters after the first one passes.

For example:

const productAvailable = true;
const quantity = 3;

if (productAvailable) {
    if (quantity > 0) {
        console.log("You can add this product");
    }
}

However, too much nesting can make code difficult to read.

Avoid Unnecessary Nesting

Instead of:

if (loggedIn) {
    if (emailVerified) {
        console.log("Account ready");
    }
}

you can often write:

if (loggedIn && emailVerified) {
    console.log("Account ready");
}

Both conditions must pass, so logical AND gives a flatter structure.

if Statements Inside Functions

Conditions are commonly used inside functions.

Example:

function checkStock(stock) {
    if (stock > 0) {
        return "In stock";
    }

    return "Out of stock";
}

console.log(checkStock(5));

Output:

In stock

You will study functions properly in the JavaScript Functions tutorial.

For now, notice that conditions can decide which value a function returns.

Early Return Pattern

As your JavaScript grows, you may see code like:

function checkAccess(loggedIn) {
    if (!loggedIn) {
        return "Please log in";
    }

    return "Welcome";
}

This handles the failed case first.

The rest of the function can then continue without extra nesting.

You do not need to use this pattern everywhere yet, but it is useful to recognize.

if Without else

You do not always need else.

For example:

const stock = 2;

if (stock < 5) {
    console.log("Low stock");
}

If the condition is false, JavaScript simply continues after the block.

Use else only when you actually need an alternative action.

else Without if Is Not Valid

This is invalid:

else {
    console.log("Hello");
}

An else must belong to an if statement.

Correct:

if (true) {
    console.log("First block");
} else {
    console.log("Second block");
}

Curly Braces in if Statements

JavaScript allows a one-line if without braces:

if (stock > 0) console.log("Available");

But beginners should prefer braces:

if (stock > 0) {
    console.log("Available");
}

Braces make the block clearer and reduce mistakes when you add more lines later.

Real Website Example: Quantity Limit

Suppose customers can order between one and five items.

const quantity = 3;

if (quantity < 1) {
    console.log("Choose at least one item");
} else if (quantity > 5) {
    console.log("Maximum quantity is five");
} else {
    console.log("Quantity accepted");
}

Output:

Quantity accepted

This is a practical form or cart validation pattern.

Real Website Example: User Role

Suppose a dashboard supports three roles.

const role = "editor";

if (role === "admin") {
    console.log("Full access");
} else if (role === "editor") {
    console.log("Editing access");
} else {
    console.log("Basic access");
}

Output:

Editing access

When you have many exact-value branches like this, a switch statement can sometimes be easier to read.

That is why the next lesson covers JavaScript switch statements.

Real Website Example: Password Length

Suppose a password must have at least eight characters.

const password = "abc123";

if (password.length >= 8) {
    console.log("Password length accepted");
} else {
    console.log("Password must contain at least 8 characters");
}

Output:

Password must contain at least 8 characters

This is only a length check, not complete password security validation.

Real Website Example: Form Status

Suppose:

const name = "Riya";
const email = "riya@example.com";

Check whether both fields contain values:

if (name && email) {
    console.log("Form ready");
} else {
    console.log("Complete all required fields");
}

Output:

Form ready

Both strings are truthy because they are not empty.

Real Website Example: Price Range

Suppose a filter should accept products between ₹500 and ₹2,000.

const price = 1200;

if (price >= 500 && price <= 2000) {
    console.log("Product is inside the selected range");
} else {
    console.log("Product is outside the selected range");
}

Output:

Product is inside the selected range

This combines two comparisons with logical AND.

Real Website Example: Delivery City

Suppose express delivery is available in Delhi or Noida.

const city = "Noida";

if (city === "Delhi" || city === "Noida") {
    console.log("Express delivery available");
} else {
    console.log("Standard delivery only");
}

Output:

Express delivery available

Using a Variable to Store a Condition

Conditions can be stored in well-named variables.

Instead of:

if (age >= 18 && hasTicket && !blocked) {
    console.log("Entry allowed");
}

you can write:

const isAdult = age >= 18;
const canEnter = isAdult && hasTicket && !blocked;

if (canEnter) {
    console.log("Entry allowed");
}

This can make complex rules easier to understand.

if else vs Ternary Operator

JavaScript has a shorter conditional operator called the ternary operator.

Example:

const age = 20;

const message = age >= 18 ? "Adult" : "Under 18";

This can be useful for a simple two-result choice.

However, beginners should first become comfortable with:

if
else if
else

before using ternary expressions everywhere.

A dedicated ternary operator lesson will cover when it helps and when normal if else is clearer.

if else vs switch

Use if else when your conditions involve:

  • Ranges
  • Greater-than or less-than checks
  • Multiple logical conditions
  • Different kinds of expressions

For example:

if (score >= 90) {
    // ...
} else if (score >= 80) {
    // ...
}

A switch statement can be useful when one value is compared against several exact choices.

For example:

admin
editor
customer

You will learn that in the JavaScript switch tutorial.

Common Beginner Mistakes

Using = Instead of ===

Wrong:

if (role = "admin") {
    console.log("Admin");
}

= assigns a value.

For comparison, use:

if (role === "admin") {
    console.log("Admin");
}

Review the JavaScript Comparison Operators lesson if needed.

Writing else if as One Word

Wrong:

elseif

Correct:

else if

They are two JavaScript keywords.

Adding a Condition After else

Wrong:

else (age < 18) {
    console.log("Under 18");
}

else does not take a condition.

Use:

else {
    console.log("Under 18");
}

Or use else if when another condition is needed.

Putting a Semicolon After if

Wrong:

if (age >= 18); {
    console.log("Adult");
}

That semicolon ends the if statement early.

Use:

if (age >= 18) {
    console.log("Adult");
}

Forgetting Curly Braces

This is valid:

if (age >= 18)
    console.log("Adult");

But it becomes easy to make mistakes when another line is added.

Prefer:

if (age >= 18) {
    console.log("Adult");
}

Putting Broad Conditions Before Specific Ones

Wrong order:

if (score >= 60) {
    console.log("Pass");
} else if (score >= 90) {
    console.log("Excellent");
}

A score of 95 matches the first condition.

Put the more specific threshold first.

Repeating the Same Condition

Avoid:

if (age >= 18) {
    console.log("Adult");
} else if (age >= 18) {
    console.log("Something else");
}

The second branch can never run.

Writing Very Deep Nested Conditions

Code like this becomes hard to follow:

if (loggedIn) {
    if (verified) {
        if (hasAccess) {
            if (!blocked) {
                console.log("Open page");
            }
        }
    }
}

Where possible, combine related conditions:

if (loggedIn && verified && hasAccess && !blocked) {
    console.log("Open page");
}

Comparing Boolean Values Unnecessarily

This works:

if (loggedIn === true) {
    console.log("Welcome");
}

But when loggedIn is already a boolean, this is simpler:

if (loggedIn) {
    console.log("Welcome");
}

Forgetting That Form Values May Be Strings

A form value may look numeric but still be text.

For example:

const age = "18";

Strict comparison:

age === 18

returns:

false

Check and convert types intentionally when needed.

Best Practices for JavaScript if else

Keep each condition easy to understand.

Prefer:

const hasStock = stock > 0;

if (hasStock) {
    console.log("Available");
}

when the named condition improves clarity.

Use strict comparisons such as:

===
!==

for predictable equality checks.

Use logical operators for related checks:

if (age >= 18 && hasTicket) {
    // ...
}

Put more specific else if conditions before broader ones.

Use curly braces even for short conditions.

Avoid unnecessary nesting.

Use else only when you actually need a fallback action.

Break long conditions into named boolean variables when the rule becomes hard to read.

Beginner Exercise

Create:

const age = 17;

Write an if else statement that prints:

Adult

when age is at least 18.

Otherwise print:

Under 18

Then change the age to:

20

and run it again.

Challenge Exercise

Create:

const cartTotal = 3500;

Use if, else if, and else with these rules:

  • ₹5,000 or more → 20% discount
  • ₹3,000 or more → 10% discount
  • ₹1,000 or more → 5% discount
  • Below ₹1,000 → No discount

Print the correct discount.

Extra Challenge

Create:

const age = 22;
const hasTicket = true;
const blocked = false;

Allow entry only when:

  • Age is at least 18
  • The user has a ticket
  • The user is not blocked

Print:

Entry allowed

or:

Entry denied

Try to solve it using one if else statement and logical operators.

Frequently Asked Questions

What is if else in JavaScript?

JavaScript if else statements let your code choose which block to run based on whether a condition is truthy or falsy.

What is the syntax of an if statement?

if (condition) {
    // code
}

The code inside the braces runs when the condition is truthy.

What is else in JavaScript?

else provides another block that runs when the related if or else if conditions do not pass.

What is else if in JavaScript?

else if lets you test another condition after an earlier if or else if condition fails.

Can I use multiple else if statements?

Yes.

You can create several else if branches when your code needs multiple possible outcomes.

Does an if statement need else?

No.

You can use an if statement by itself when no fallback action is needed.

Can else have a condition?

No.

Use else if when another condition is required.

Can I use && inside an if statement?

Yes.

Use && when all required conditions must pass.

if (age >= 18 && hasTicket) {
    // ...
}

Can I use || inside an if statement?

Yes.

Use || when one of several conditions is enough.

if (isAdmin || isEditor) {
    // ...
}

Can I use ! inside an if statement?

Yes.

! reverses the truthiness of a value.

if (!loggedIn) {
    console.log("Please log in");
}

What is a nested if statement?

A nested if is an if statement placed inside another if block.

It can be useful, but too much nesting makes code harder to read.

What is the difference between if else and switch?

if else is flexible for ranges, comparisons, and combined conditions.

switch is often useful when one value is checked against several exact choices.

What is the difference between if else and the ternary operator?

A ternary expression is a shorter way to choose between two values.

if else is usually clearer for larger or more complex logic.

Why is my else if not running?

A previous condition may already be true.

JavaScript stops an if else if chain after the first matching branch.

Check the order of your conditions.

Should I use == or === inside if statements?

For most modern JavaScript code, prefer === because it compares both value and type without loose type conversion.

What should I learn after JavaScript if else?

Learn the JavaScript switch statement next. It provides another way to choose between several exact values.

Summary

JavaScript if else statements let your code make decisions.

Use:

if

to run code when a condition passes.

Use:

else

for a fallback action.

Use:

else if

when another condition needs to be checked.

For example:

const stock = 5;

if (stock > 0) {
    console.log("In stock");
} else {
    console.log("Out of stock");
}

You also learned how to use conditions with:

  • Comparison operators
  • Logical AND &&
  • Logical OR ||
  • Logical NOT !
  • Truthy and falsy values
  • Multiple else if branches
  • Nested conditions
  • Real website rules

Keep specific conditions before broader ones, use curly braces, prefer strict comparisons, and avoid unnecessarily deep nesting.

These skills prepare you to handle more complex website behavior.

Continue Learning JavaScript

Previous Lesson: JavaScript Logical Operators Explained

Course Home: JavaScript Tutorial for Beginners

Next Lesson: JavaScript switch Statement Explained

In the next lesson, you will learn how switch, case, break, and default work when one value can match several exact choices.

James Parker

James Parker

James Parker is a technology writer and WordPress enthusiast who shares practical guides on SEO, web development, AI tools, and digital growth. He focuses on creating easy-to-follow tutorials that help beginners and professionals build better websites and improve their online presence.