Ad – 728Γ—90
πŸ”€ Control Flow

JavaScript If Statements – Conditionals Explained

Learn how to make your programs decide what to do using JavaScript's conditional statements. From simple if/else blocks to ternary operators and short-circuit tricks, this guide covers everything you need to write smart, expressive logic.

⏱️ 18 min read 🎯 Beginner πŸ“… Updated 2026

What Is an If Statement?

An if statement tells JavaScript to run a block of code only when a condition is true. It is the most fundamental decision-making tool in the language.

JavaScript
let temperature = 30;

if (temperature > 25) {
  console.log("It's hot outside!");
}
β–Ά Output
It's hot outside!

If the condition evaluates to false, the entire block is skipped and execution continues after the closing brace.

if / else

Add an else block to handle the case when the condition is false.

JavaScript
let age = 16;

if (age >= 18) {
  console.log("You can vote.");
} else {
  console.log("You are too young to vote.");
}
β–Ά Output
You are too young to vote.

else if Chain

Chain multiple conditions with else if. JavaScript evaluates each condition from top to bottom and runs the first matching block.

JavaScript
let score = 75;

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("Grade: F");
}
β–Ά Output
Grade: C
πŸ’‘
Order Matters

Always put the most specific (narrowest) condition first. If you put score >= 60 at the top, everyone with a score β‰₯ 60 would get a "D" β€” the rest would never be reached.

Comparison Operators in Conditions

OperatorMeaningExampleResult
==Loose equal5 == "5"true
===Strict equal5 === "5"false
!=Loose not equal5 != "6"true
!==Strict not equal5 !== "5"true
>Greater than10 > 5true
<Less than3 < 7true
>=Greater or equal5 >= 5true
<=Less or equal4 <= 3false
⚠️
Always Use === Over ==

Loose equality (==) performs type coercion and can produce surprising results like 0 == false being true. Prefer strict equality (===) in nearly every situation.

Truthy and Falsy Values

Every JavaScript value is either truthy or falsy when used in a boolean context. There are only six falsy values:

JavaScript
// The six falsy values
if (false)     { /* never runs */ }
if (0)         { /* never runs */ }
if (-0)        { /* never runs */ }
if ("")        { /* never runs */ }
if (null)      { /* never runs */ }
if (undefined) { /* never runs */ }
if (NaN)       { /* never runs */ }

// Everything else is truthy
if ("hello")   { console.log("truthy string"); }
if (1)         { console.log("truthy number"); }
if ([])        { console.log("empty array is truthy!"); }
if ({})        { console.log("empty object is truthy!"); }
β–Ά Output
truthy string truthy number empty array is truthy! empty object is truthy!
ℹ️
Empty Array and Object Are Truthy

This surprises many beginners. [] and {} are objects, and all objects are truthy. To check if an array is empty, compare arr.length === 0 instead.

Logical Operators in Conditions

Combine conditions using && (AND), || (OR), and ! (NOT).

JavaScript
let isLoggedIn = true;
let isAdmin = false;
let username = "Alice";

// AND β€” both must be true
if (isLoggedIn && isAdmin) {
  console.log("Welcome, admin!");
}

// OR β€” at least one must be true
if (isLoggedIn || isAdmin) {
  console.log("Access granted.");
}

// NOT β€” inverts the boolean
if (!isAdmin) {
  console.log("You are not an admin.");
}

// Combining operators with parentheses
if (isLoggedIn && (isAdmin || username === "Alice")) {
  console.log("Special access for Alice.");
}
β–Ά Output
Access granted. You are not an admin. Special access for Alice.

Short-Circuit Evaluation

JavaScript stops evaluating a condition as soon as the result is known:

  • && stops at the first falsy value and returns it
  • || stops at the first truthy value and returns it
JavaScript
// || used for default values
let userName = "";
let displayName = userName || "Guest";
console.log(displayName); // "Guest"

// && used to safely access properties
let user = null;
let city = user && user.address && user.address.city;
console.log(city); // null (short-circuited, no error)

// Practical: default parameter before ES6
function greet(name) {
  name = name || "Stranger";
  console.log("Hello, " + name + "!");
}
greet();         // Hello, Stranger!
greet("Bob");    // Hello, Bob!
β–Ά Output
Guest null Hello, Stranger! Hello, Bob!

Ternary Operator (?:)

The ternary operator is a compact one-liner for simple if/else logic: condition ? valueIfTrue : valueIfFalse.

JavaScript
let age = 20;

// Traditional if/else
let status;
if (age >= 18) {
  status = "adult";
} else {
  status = "minor";
}

// Equivalent ternary
let status2 = age >= 18 ? "adult" : "minor";
console.log(status2); // adult

// Inline in template literals
console.log(`You are a${age >= 18 ? "n adult" : " minor"}.`);

// Ternary for JSX / HTML generation
let role = "editor";
let badge = role === "admin" ? "πŸ›‘οΈ Admin" : role === "editor" ? "✏️ Editor" : "πŸ‘€ User";
console.log(badge); // ✏️ Editor
β–Ά Output
adult You are an adult. ✏️ Editor
⚠️
Avoid Chaining Ternaries

Nested ternaries like a ? b : c ? d : e become hard to read. If you need more than one level, use an if/else chain instead.

Nested If β€” A Quick Look

You can place an if statement inside another if block. Keep nesting shallow to preserve readability.

JavaScript
let isLoggedIn = true;
let hasPremium = true;

if (isLoggedIn) {
  if (hasPremium) {
    console.log("Watch premium content.");
  } else {
    console.log("Upgrade to premium.");
  }
} else {
  console.log("Please log in.");
}
β–Ά Output
Watch premium content.

Real-World Examples

Age Category Checker

JavaScript
function getAgeCategory(age) {
  if (age < 0) return "Invalid age";
  if (age < 13) return "Child";
  if (age < 18) return "Teenager";
  if (age < 65) return "Adult";
  return "Senior";
}

console.log(getAgeCategory(10));  // Child
console.log(getAgeCategory(16));  // Teenager
console.log(getAgeCategory(30));  // Adult
console.log(getAgeCategory(70));  // Senior
β–Ά Output
Child Teenager Adult Senior

Login Validation

JavaScript
function login(username, password) {
  if (!username || !password) {
    return "Error: Username and password are required.";
  }
  if (username === "admin" && password === "secret") {
    return "Welcome, admin!";
  }
  return "Invalid credentials.";
}

console.log(login("", "secret"));          // Error: Username and password are required.
console.log(login("admin", "secret"));     // Welcome, admin!
console.log(login("user", "wrong"));       // Invalid credentials.
β–Ά Output
Error: Username and password are required. Welcome, admin! Invalid credentials.
Ad – 336Γ—280

πŸ‹οΈ Practical Exercise

Write a function getTicketPrice(age, isStudent) that returns a ticket price:

  • Under 5: Free (0)
  • 5–17 or student: $8
  • 18–64: $15
  • 65 and above: $10

Test with: getTicketPrice(3, false), getTicketPrice(20, true), getTicketPrice(25, false), getTicketPrice(70, false).

πŸ”₯ Challenge Exercise

Build a fizzBuzz(n) function using if/else if/else that:

  • Returns "FizzBuzz" if n is divisible by both 3 and 5
  • Returns "Fizz" if divisible by 3
  • Returns "Buzz" if divisible by 5
  • Returns the number as a string otherwise

Then call it for numbers 1 through 20 in a loop. Use the ternary operator to rewrite it in one expression.

πŸ“‹ Summary

  • if (condition) {} runs code only when condition is truthy.
  • else if chains let you test multiple conditions in order.
  • Six falsy values: false, 0, "", null, undefined, NaN.
  • Always use === (strict equality) instead of ==.
  • Short-circuit: || returns first truthy; && returns first falsy.
  • Ternary condition ? a : b is concise for simple if/else β€” avoid nesting it.

Interview Questions

  • What is the difference between == and === in JavaScript?
  • List all falsy values in JavaScript. What is surprising about empty arrays?
  • Explain short-circuit evaluation. How is it used as a default-value pattern?
  • When would you choose a ternary operator over an if/else statement?
  • What is the difference between && and || returning a value vs. a boolean?

Frequently Asked Questions

Can I write an if statement without curly braces?+

Yes, you can omit braces when there is only one statement: if (x > 0) console.log("positive");. However, this is error-prone when you later add a second line and forget the braces. Most style guides require braces always.

What is the difference between if/else and switch?+

Both handle conditional branching. Use switch when comparing one variable against many discrete values. Use if/else for range checks (age > 18) or complex boolean expressions.

Is the ternary operator faster than if/else?+

No, there is no meaningful performance difference. Choose based on readability. Simple value assignments are fine as ternary; complex logic belongs in if/else blocks.

Why does if ([]) {} run the block?+

Because an empty array [] is an object, and all objects are truthy in JavaScript. To test if an array is empty, use if (arr.length === 0).