JavaScript If...Else

Conditional statements control the flow of code based on conditions. JavaScript has if, else, else if, and the ternary operator.

The if Statement

Use the if statement to execute a block of code only when a condition is true.

if Statement
let hour = 14;

if (hour < 18) {
    console.log("Good day!");   // runs because 14 < 18
}

The else Statement

Use else to specify code to run when the condition is false.

if...else
let hour = 20;

if (hour < 18) {
    console.log("Good day!");
} else {
    console.log("Good evening!");  // runs because 20 >= 18
}

The else if Statement

Use else if to test multiple conditions in sequence.

if...else if...else
let hour = 9;

if (hour < 10) {
    console.log("Good morning!");
} else if (hour < 18) {
    console.log("Good day!");
} else {
    console.log("Good evening!");
}

The Ternary Operator

The ternary operator is a shorthand if...else. Syntax: condition ? valueIfTrue : valueIfFalse

Ternary Operator
let age = 20;
let access = (age >= 18) ? "Allowed" : "Denied";
console.log(access);   // "Allowed"

// Equivalent if/else:
let score = 85;
let grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";
console.log(grade);    // "B"

Nested if Statements

Nested if
let score = 85;
let passed = true;

if (passed) {
    if (score >= 90) {
        console.log("Grade: A");
    } else if (score >= 80) {
        console.log("Grade: B");
    } else {
        console.log("Grade: C");
    }
} else {
    console.log("Failed");
}
StatementWhen to Use
ifExecute code only when condition is true
if...elseChoose between two code paths
else ifTest multiple conditions in sequence
ternary ?:Short inline if/else for simple values
📝 Note: Always use curly braces {} for code blocks, even for single-line statements. It prevents hard-to-find bugs.
Exercise:
Which keyword catches all remaining conditions in an if...else chain?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.