Skip to main content
โšก Calmops

Conditional Statements in JavaScript

Conditional Statements in JavaScript

Conditional statements let your code make decisions and execute different code based on conditions.

if Statement

The most basic conditional:

if (condition) {
    // Code runs if condition is true
}

Example

const age = 18;

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

if…else Statement

Execute different code based on a condition:

if (condition) {
    // Runs if true
} else {
    // Runs if false
}

Example

const age = 15;

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

if…else if…else Statement

Check multiple conditions:

const 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 {
    console.log("Grade: F");
}

Nested if Statements

Conditions inside conditions:

const age = 20;
const hasLicense = true;

if (age >= 18) {
    if (hasLicense) {
        console.log("You can drive");
    } else {
        console.log("You need a license");
    }
} else {
    console.log("You are too young to drive");
}

Logical Operators

AND (&&)

Both conditions must be true:

const age = 20;
const hasLicense = true;

if (age >= 18 && hasLicense) {
    console.log("You can drive");
}

OR (||)

At least one condition must be true:

const isWeekend = true;
const isHoliday = false;

if (isWeekend || isHoliday) {
    console.log("No work today!");
}

NOT (!)

Reverses the condition:

const isRaining = false;

if (!isRaining) {
    console.log("Let's go outside");
}

switch Statement

Check a value against multiple cases:

const day = "Monday";

switch (day) {
    case "Monday":
        console.log("Start of the week");
        break;
    case "Friday":
        console.log("Almost weekend");
        break;
    case "Saturday":
    case "Sunday":
        console.log("Weekend!");
        break;
    default:
        console.log("Midweek");
}

Important: break Statement

Without break, execution continues to the next case (fall-through):

const fruit = "apple";

switch (fruit) {
    case "apple":
        console.log("Red or green");
        // Missing break - falls through!
    case "banana":
        console.log("Yellow");
        break;
    case "orange":
        console.log("Orange");
        break;
}
// Output: "Red or green" and "Yellow"

default Case

Runs if no cases match:

const color = "purple";

switch (color) {
    case "red":
        console.log("Stop");
        break;
    case "yellow":
        console.log("Caution");
        break;
    case "green":
        console.log("Go");
        break;
    default:
        console.log("Unknown color");
}

Ternary Operator

Shorthand for if…else:

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

Syntax

condition ? valueIfTrue : valueIfFalse

Nested Ternary

const score = 75;
const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";
console.log(grade); // "C"

Note: Nested ternaries can be hard to read. Use if…else for complex logic.

Truthy and Falsy Values

Falsy Values

These are considered false in conditions:

if (false) { } // false
if (0) { } // zero
if ("") { } // empty string
if (null) { } // null
if (undefined) { } // undefined
if (NaN) { } // Not a Number

Truthy Values

Everything else is true:

if (true) { } // true
if (1) { } // any non-zero number
if ("text") { } // any non-empty string
if ([]) { } // arrays (even empty!)
if ({}) { } // objects (even empty!)

Practical Examples

Validating User Input

function validatePassword(password) {
    if (!password) {
        return "Password is required";
    }
    
    if (password.length < 8) {
        return "Password must be at least 8 characters";
    }
    
    if (!/[A-Z]/.test(password)) {
        return "Password must contain uppercase letter";
    }
    
    if (!/[0-9]/.test(password)) {
        return "Password must contain a number";
    }
    
    return "Password is valid";
}

console.log(validatePassword("weak")); // "Password must be at least 8 characters"
console.log(validatePassword("Strong123")); // "Password is valid"

Determining Discount

function getDiscount(purchaseAmount) {
    if (purchaseAmount >= 1000) {
        return 0.20; // 20% discount
    } else if (purchaseAmount >= 500) {
        return 0.15; // 15% discount
    } else if (purchaseAmount >= 100) {
        return 0.10; // 10% discount
    } else {
        return 0; // No discount
    }
}

const amount = 750;
const discount = getDiscount(amount);
const finalPrice = amount * (1 - discount);
console.log(`Discount: ${discount * 100}%, Final Price: $${finalPrice}`);

User Role Authorization

function checkAccess(userRole, action) {
    if (userRole === "admin") {
        return true; // Admins can do anything
    }
    
    if (userRole === "editor" && (action === "read" || action === "write")) {
        return true;
    }
    
    if (userRole === "viewer" && action === "read") {
        return true;
    }
    
    return false;
}

console.log(checkAccess("admin", "delete")); // true
console.log(checkAccess("editor", "write")); // true
console.log(checkAccess("viewer", "write")); // false

Best Practices

Use Meaningful Conditions

// Good
const isAdult = age >= 18;
if (isAdult) {
    // ...
}

// Less clear
if (age >= 18) {
    // ...
}

Avoid Deep Nesting

// Good - early return
function processUser(user) {
    if (!user) return "No user";
    if (!user.email) return "No email";
    if (!user.verified) return "Not verified";
    
    return "Process user";
}

// Avoid - deep nesting
function processUser(user) {
    if (user) {
        if (user.email) {
            if (user.verified) {
                return "Process user";
            }
        }
    }
}

Use switch for Multiple Cases

// Good - switch for many cases
switch (status) {
    case "pending": // ...
    case "active": // ...
    case "inactive": // ...
}

// Avoid - many if...else
if (status === "pending") { }
else if (status === "active") { }
else if (status === "inactive") { }

Summary

  • if…else: Execute code based on conditions
  • switch: Check value against multiple cases
  • Ternary operator: Shorthand for simple if…else
  • Logical operators: AND (&&), OR (||), NOT (!)
  • Truthy/Falsy: Understand what evaluates to true/false
  • Best practices: Keep conditions readable, avoid deep nesting

Official Documentation

Next Steps

  1. Loops in JavaScript (for, while, for…of, for…in)
  2. JavaScript Operators: Arithmetic, Logical, Comparison
  3. Functions: Definition, Parameters, Return Values

Comments