JavaScript Guide
Beginner11 minsJS Tutorial

JavaScript If Else

Master JavaScript conditional statements — if, else if, else, nested conditions, ternary operator, and logical short-circuit patterns.

Lesson session

0% complete

0/5
Learn mode

Read the concept first, then inspect syntax and examples.

Study prompt

Current mode guidance

Read the concept first, then inspect syntax and examples.

Confidence

Track your comfort

55%
NewClear

Quick notes

0/240 characters

Concept switcher

Move through the idea before the code.

Conditional statements let your program make decisions — run different code based on whether a condition is true or false.

This is the fundamental logic structure that makes programs intelligent. Without it, every program would do the same thing regardless of input:

// Without conditions: always the same
console.log("Welcome!");  // Same for everyone

// With conditions: smart behavior
const hour = new Date().getHours();

if (hour < 12) {
  console.log("Good Morning!");
} else if (hour < 17) {
  console.log("Good Afternoon!");
} else {
  console.log("Good Evening!");
}

Every real application uses conditions constantly: authentication checks, form validation, feature flags, pricing logic, access control, and UI state management.

Example preview

Run it in your head

if/else if/else — Grading System

Classic multi-condition example — exactly what you'd build in real apps.

function getGrade(marks) {
  if (marks < 0 || marks > 100) {
    return "Invalid marks (must be 0-100)";
  }
  
  if (marks >= 90) return "A+ — Excellent!";
  if (marks >= 80) return "A — Very Good";
  if (marks >= 70) return "B — Good";
  if (marks >= 60) return "C — Average";
  if (marks >= 50) return "D — Below Average";
  return "F — Fail";
}

const students = [
  { name: "Asha", marks: 95 },
  { name: "Ravi", marks: 78 },
  { name: "Priya", marks: 55 },
  { name: "Mira", marks: 42 },
  { name: "Karan", marks: 88 }
];

students.forEach(student => {
  console.log(student.name + ": " + getGrade(student.marks));
});
Output

Predict the output first, then reveal it.

Next useful links

Related pages from the same JavaScript guide.

Overview & Purpose

Conditional statements let your program make decisions — run different code based on whether a condition is true or false.

This is the fundamental logic structure that makes programs intelligent. Without it, every program would do the same thing regardless of input:

// Without conditions: always the same
console.log("Welcome!");  // Same for everyone

// With conditions: smart behavior
const hour = new Date().getHours();

if (hour < 12) {
  console.log("Good Morning!");
} else if (hour < 17) {
  console.log("Good Afternoon!");
} else {
  console.log("Good Evening!");
}

Every real application uses conditions constantly: authentication checks, form validation, feature flags, pricing logic, access control, and UI state management.

Topic Definition

JavaScript provides several ways to handle conditions:

| Syntax | Best For |

|--------|----------|

| `if (condition)` | Single condition |

| `if/else` | Two outcomes |

| `if/else if/else` | Multiple conditions |

| **Ternary** `condition ? a : b` | Inline expressions |

| **Logical &&** `cond && action` | Execute if true |

| **Nullish coalescing ??** `val ?? default` | Fallback for null/undefined |

| `switch/case` | Multiple values of same variable |

Why It Matters

Programs without conditions are just scripts — they do the same thing every time. Conditions create behavior that responds to data:

User role = admin → show admin panel

Form field = empty → show error message

Cart total > 1000 → apply free shipping

API returns error → show error state

Mobile device → show mobile layout

Dark mode enabled → apply dark theme

Syntax Guide

javascript
// ═══════════════════════════════════════════════
// 1. BASIC if
// ═══════════════════════════════════════════════
const age = 20;
if (age >= 18) {
  console.log("Access granted");
}

// ═══════════════════════════════════════════════
// 2. if / else
// ═══════════════════════════════════════════════
const balance = 500;
if (balance >= 1000) {
  console.log("Order placed");
} else {
  console.log("Insufficient balance");
}

// ═══════════════════════════════════════════════
// 3. if / else if / else (multiple conditions)
// ═══════════════════════════════════════════════
const score = 78;
if (score >= 90) {
  console.log("Grade: A+");
} else if (score >= 80) {
  console.log("Grade: A");
} else if (score >= 70) {
  console.log("Grade: B");
} else if (score >= 60) {
  console.log("Grade: C");
} else {
  console.log("Grade: F");
}

// ═══════════════════════════════════════════════
// 4. TERNARY OPERATOR (inline if/else)
// ═══════════════════════════════════════════════
const isLoggedIn = true;
const message = isLoggedIn ? "Welcome back!" : "Please log in";
console.log(message);

// ═══════════════════════════════════════════════
// 5. LOGICAL SHORT-CIRCUIT (&& and ||)
// ═══════════════════════════════════════════════
const user = { name: "Asha", isAdmin: true };

// && — execute right side only if left is truthy
user.isAdmin && console.log("Show admin panel");

// || — use fallback if left is falsy
const displayName = user.nickname || user.name || "Anonymous";
console.log(displayName);
Reference API Specifications
Parameters:
  • condition — any expression that evaluates to truthy or falsy
  • Truthy values — non-zero numbers, non-empty strings, objects, arrays, true
  • Falsy values — 0, '' (empty string), null, undefined, NaN, false
  • Comparison operators — === !== < > <= >= for building conditions
  • Logical operators — && (and), || (or), ! (not) for combining conditions
Return Value:

if/else statements don't return values. The ternary operator returns one of two values. Use ternary when you need a value, if/else when you need to execute statements.

Syntax Explanation:

Truthy and Falsy — Critical Concept:

In JavaScript, every value is either truthy (treated as true in conditions) or falsy (treated as false):

Falsy values (memorize these 6):
  false, 0, "" (empty string), null, undefined, NaN

Everything else is truthy — including:
  "0" (string zero), [] (empty array), {} (empty object)

This matters because:

const username = "";  // empty string = FALSY
if (username) {
  console.log("Valid"); // won't run
} else {
  console.log("Invalid"); // runs ← empty string is falsy
}

const cart = [];  // empty array = TRUTHY (common surprise!)
if (cart) {
  console.log("Cart exists"); // runs! [] is truthy
}
if (cart.length > 0) {
  console.log("Cart has items"); // won't run — correct check
}

Early return pattern (cleaner than nested if):

// ❌ Nested — hard to read
function processOrder(order) {
  if (order) {
    if (order.items.length > 0) {
      if (order.payment === "paid") {
        // process
      }
    }
  }
}

// ✅ Early return — flat and readable
function processOrder(order) {
  if (!order) return "No order";
  if (order.items.length === 0) return "Empty cart";
  if (order.payment !== "paid") return "Not paid";
  
  // Main logic here — clean!
  return "Processing...";
}

Runnable Code Examples

Example 1: if/else if/else — Grading System

Classic multi-condition example — exactly what you'd build in real apps.

javascript
function getGrade(marks) {
  if (marks < 0 || marks > 100) {
    return "Invalid marks (must be 0-100)";
  }
  
  if (marks >= 90) return "A+ — Excellent!";
  if (marks >= 80) return "A — Very Good";
  if (marks >= 70) return "B — Good";
  if (marks >= 60) return "C — Average";
  if (marks >= 50) return "D — Below Average";
  return "F — Fail";
}

const students = [
  { name: "Asha", marks: 95 },
  { name: "Ravi", marks: 78 },
  { name: "Priya", marks: 55 },
  { name: "Mira", marks: 42 },
  { name: "Karan", marks: 88 }
];

students.forEach(student => {
  console.log(student.name + ": " + getGrade(student.marks));
});
expected console output
Asha: A+ — Excellent! Ravi: B — Good Priya: D — Below Average Mira: F — Fail Karan: A — Very Good
Breakdown:

Early returns flatten the if/else chain — no nested braces. JavaScript checks conditions top to bottom, stops at the first true one. The boundary case (invalid marks) is checked first.

Example 2: Ternary Operator — Inline Decisions

Perfect for assigning values based on conditions.

javascript
// ─── Simple ternary ──────────────────────────────────────────────
const isLoggedIn = true;
const buttonText = isLoggedIn ? "Logout" : "Login";
console.log(buttonText); // Logout

// ─── Ternary in JSX-style string template ──────────────────────────
const cartCount = 3;
const cartDisplay = cartCount > 0
  ? "Cart (" + cartCount + " items)"
  : "Cart (empty)";
console.log(cartDisplay); // Cart (3 items)

// ─── Ternary for class names (common in React) ─────────────────────
const isDarkMode = false;
const theme = isDarkMode ? "dark-theme" : "light-theme";
console.log("Theme:", theme);

// ─── Nested ternary (use sparingly) ───────────────────────────────
const score = 75;
const grade = score >= 90 ? "A"
  : score >= 70 ? "B"
  : score >= 50 ? "C"
  : "F";
console.log("Grade:", grade);
expected console output
Logout Cart (3 items) Theme: light-theme Grade: B
Breakdown:

Ternary is perfect for conditional VALUE assignment. It returns a value (unlike if/else which executes statements). For complex conditions, use if/else — nested ternaries quickly become unreadable.

Example 3: Logical Operators — Short-Circuit Evaluation

Powerful patterns using && and || for concise conditional logic.

javascript
// ── && (AND): execute right side ONLY if left is truthy ────────────
const user = { name: "Asha", isAdmin: true, isVerified: true };

// Classic pattern: condition && action
user.isAdmin && console.log("Admin panel available");
user.isVerified && user.isAdmin && console.log("Super admin confirmed");

// ── || (OR): use fallback if left is falsy ────────────────────────
const username = "";          // empty string = falsy
const displayName = username || "Anonymous User";
console.log(displayName);     // Anonymous User

const config = null;
const timeout = config?.timeout || 3000;  // default 3 seconds
console.log("Timeout:", timeout);

// ── ?? (Nullish Coalescing): fallback for null/undefined ONLY ─────
const count = 0;
console.log(count || "No count");    // "No count" ← 0 is falsy!
console.log(count ?? "No count");   // 0 ← 0 is not null/undefined ✅

// ── Real pattern: guard clause ──────────────────────────────────────
function updateProfile(userId, data) {
  if (!userId) return { error: "User ID required" };
  if (!data || Object.keys(data).length === 0) return { error: "No data provided" };
  
  return { success: true, message: "Profile updated" };
}

console.log(updateProfile(null, { name: "Asha" }));
console.log(updateProfile(42, {}));
console.log(updateProfile(42, { name: "Asha" }));
expected console output
Admin panel available Super admin confirmed Anonymous User Timeout: 3000 No count 0 { error: 'User ID required' } { error: 'No data provided' } { success: true, message: 'Profile updated' }
Breakdown:

&& executes right side only if left is truthy (guard). || uses the right side when left is falsy (default). ?? (nullish coalescing) uses fallback only for null/undefined — safer than || when 0 or '' are valid values.

Real-world Use Cases

  • 1

    Authentication gates: if (!isLoggedIn) { redirect('/login'); return; } — protects protected routes.

  • 2

    Form validation: Check each field before submission: if (!email.includes('@')) { showError('Invalid email'); return; }

  • 3

    Feature flags: if (featureFlags.newCheckout) { renderNewCheckout() } else { renderOldCheckout() }

  • 4

    Role-based UI: if (user.role === 'admin') { showAdminButton() } — shows/hides UI elements based on permissions.

  • 5

    API error handling: if (response.ok) { return response.json() } else { throw new Error(response.statusText) }

  • 6

    Pricing logic: Free shipping if total > 1000, calculate discount based on cart size, tier-based pricing.

Coding Exercises

1

Exercise Challenge

Write a function calculateShipping(orderTotal, membershipLevel) with: free if total >= 2000, free if premium member, ₹99 if standard member, ₹149 otherwise.

Practice Tasks Checklist

1Write a function that returns appropriate tax rate based on product category.
2Build a login validation: check username and password, return appropriate error messages.
3Create a shipping calculator: free if > ₹500, ₹49 if 200-500, ₹99 below 200.
4Rewrite a 5-level nested if/else using early returns.
5Use the ternary operator to assign CSS class names based on multiple conditions.
6Create an access control function using multiple && and || conditions.
7Write a function that uses ?? to safely access nested object properties.
8Build a feature flag system with conditional rendering.
9Implement a simple state machine using if/else (e.g., order status transitions).
10Demonstrate the [] empty array truthy trap and explain the fix.

JavaScript If Else Quiz Challenges

1

Quiz Challenge

Which of these values is TRUTHY in JavaScript?

2

Quiz Challenge

What is the ternary operator syntax?

Technical Interview Q&As

1What values are falsy in JavaScript?

Model Answer:

There are exactly 6 falsy values: false, 0 (and -0), '' or '' (empty string), null, undefined, and NaN. Everything else is truthy — including '0' (string), [] (empty array), {} (empty object). Knowing this is crucial because if conditions use truthy/falsy evaluation.
2What is the difference between = (assignment), == (loose equality), and === (strict equality)?

Model Answer:

= assigns a value: `x = 5` makes x equal 5. == (loose equality) converts types before comparing: '5' == 5 is true, 0 == false is true. === (strict equality) compares both value AND type without conversion: '5' === 5 is false, 0 === false is false. Always use === in production code to avoid type coercion bugs.
3What is the difference between || and ?? (nullish coalescing)?

Model Answer:

|| (OR) uses the right side when the left is ANY falsy value (false, 0, '', null, undefined, NaN). ?? (nullish coalescing) uses the right side ONLY when the left is null or undefined. Example: const count = 0; count || 10 gives 10 (wrong! 0 is valid); count ?? 10 gives 0 (correct!). Use ?? when 0 or empty string are valid values.

Related Lessons

Frequently Asked Questions