Web Development /JavaScript Programming / Lesson
Web Development

JavaScript Conditional Statements: if, else, else if and switch

Learn how JavaScript makes decisions using if, else, else if and switch statements to create dynamic and intelligent web applications.

🎯

Learning Objectives

["Understand why conditional statements are important in JavaScript.","Use if statements to execute code when a condition is true.","Use else statements to provide an alternative path when a condition is false.","Use else if to evaluate multiple conditions in sequence.","Understand how comparison and logical operators work with conditional statements.","Use nested conditional statements appropriately.","Understand the difference between truthy and falsy values in conditions.","Use the switch statement for multiple fixed-value choices.","Understand the role of break and default in switch statements.","Choose an appropriate conditional structure for a programming problem."]

📖

Lesson Content

Introduction

Web applications constantly need to make decisions. A website may need to determine whether a user is logged in, whether a form is valid, whether a product is available, whether a student has passed an assessment, or which message should be displayed on a page.

JavaScript provides conditional statements for making these decisions.

A conditional statement evaluates a condition and determines which block of code should run based on the result.

The main conditional structures covered in this lesson are:

  • if
  • if...else
  • if...else if...else
  • Nested conditions
  • switch

1. What Is a Condition?

A condition is an expression that can be evaluated as either true or false.

For example:

age >= 18

If age is 20, the condition is true.

If age is 15, the condition is false.

Conditions are commonly created using comparison operators such as:

  • === — strictly equal
  • !== — strictly not equal
  • > — greater than
  • < — less than
  • >= — greater than or equal to
  • <= — less than or equal to

Logical operators can also combine multiple conditions:

  • && — AND
  • || — OR
  • ! — NOT

2. The if Statement

The if statement runs a block of code only when its condition evaluates to true.

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

Example:

const age = 20;

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

Because the value of age is 20, the condition is true and the message is displayed.

If the condition is false, the code inside the block is skipped.


3. The if…else Statement

Sometimes a program needs to choose between two possible paths.

The if...else statement allows you to define both paths.

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

Example:

const score = 65;

if (score >= 50) {
    console.log("You passed.");
} else {
    console.log("You failed.");
}

If the score is 50 or higher, the first block runs. Otherwise, the second block runs.


4. The else if Statement

When there are more than two possible outcomes, you can use else if.

if (condition1) {
    // First condition
} else if (condition2) {
    // Second condition
} else {
    // If all conditions are false
}

Example:

const score = 82;

if (score >= 70) {
    console.log("Grade A");
} else if (score >= 60) {
    console.log("Grade B");
} else if (score >= 50) {
    console.log("Grade C");
} else {
    console.log("Grade F");
}

JavaScript checks the conditions from top to bottom.

Once it finds a condition that is true, its corresponding block runs and the remaining conditions are skipped.


5. Order Matters in Conditions

The order of conditions can affect the result.

Consider:

const score = 85;

if (score >= 50) {
    console.log("Grade C or higher");
} else if (score >= 70) {
    console.log("Grade A");
}

The first condition is already true for 85, so JavaScript never reaches the else if.

A better structure is:

const score = 85;

if (score >= 70) {
    console.log("Grade A");
} else if (score >= 60) {
    console.log("Grade B");
} else if (score >= 50) {
    console.log("Grade C");
} else {
    console.log("Grade F");
}

When using ranges, arrange conditions carefully so that more specific or higher-priority conditions are checked before broader conditions.


6. Comparing Values

Conditional statements frequently use comparison operators.

const temperature = 30;

if (temperature > 25) {
    console.log("It is warm.");
}

Another example:

const password = "abc123";

if (password === "abc123") {
    console.log("Password accepted.");
}

The strict equality operator === compares both value and type.

In modern JavaScript, prefer === and !== when you need predictable comparisons.


7. Combining Conditions with Logical Operators

AND Operator

The && operator requires both conditions to be true.

const age = 20;
const hasID = true;

if (age >= 18 && hasID === true) {
    console.log("Access granted.");
}

OR Operator

The || operator requires at least one condition to be true.

const isAdmin = false;
const isInstructor = true;

if (isAdmin || isInstructor) {
    console.log("You can access this section.");
}

NOT Operator

The ! operator reverses a boolean value.

const loggedIn = false;

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

8. Nested if Statements

A conditional statement can contain another conditional statement. This is called a nested condition.

const age = 22;
const hasAccount = true;

if (age >= 18) {
    if (hasAccount) {
        console.log("Welcome to your dashboard.");
    }
}

Nested conditions can be useful, but excessive nesting can make code difficult to read.

When possible, logical operators can sometimes produce a simpler solution:

if (age >= 18 && hasAccount) {
    console.log("Welcome to your dashboard.");
}

9. Truthy and Falsy Values

JavaScript conditions do not always require an explicit comparison.

JavaScript can treat certain values as truthy or falsy.

Common falsy values include:

  • false
  • 0
  • ""
  • null
  • undefined
  • NaN

Most other values are truthy.

Example:

const username = "Ade";

if (username) {
    console.log("Username provided.");
}

Because the string contains a value, the condition is truthy.

Example with an empty string:

const username = "";

if (username) {
    console.log("Username provided.");
} else {
    console.log("Username is missing.");
}

10. The switch Statement

The switch statement is useful when you need to compare one value against several fixed values.

Basic structure:

switch (expression) {
    case value1:
        // Code
        break;

    case value2:
        // Code
        break;

    default:
        // Code when no case matches
}

Example:

const day = "Monday";

switch (day) {
    case "Monday":
        console.log("Start of the work week.");
        break;

    case "Friday":
        console.log("Almost the weekend.");
        break;

    case "Saturday":
        console.log("Weekend.");
        break;

    case "Sunday":
        console.log("Weekend.");
        break;

    default:
        console.log("Regular weekday.");
}

11. Understanding break

The break statement stops the switch statement from continuing into the following cases.

Without break, JavaScript can continue executing subsequent cases. This behavior is called fall-through.

For example:

const number = 1;

switch (number) {
    case 1:
        console.log("One");
        break;

    case 2:
        console.log("Two");
        break;

    default:
        console.log("Unknown number");
}

The break after case 1 prevents case 2 from executing.


12. The default Case

The default block runs when none of the cases match.

const role = "guest";

switch (role) {
    case "admin":
        console.log("Administrator");
        break;

    case "student":
        console.log("Student");
        break;

    default:
        console.log("Guest user");
}

The default case acts similarly to the final else in an if/else chain.


13. if/else versus switch

Both structures can make decisions, but they are useful in different situations.

Use if/else when:

  • You are comparing ranges.
  • You need complex logical conditions.
  • You are combining multiple expressions.
  • You need comparisons such as greater than or less than.

Use switch when:

  • You are checking one expression against several fixed values.
  • You have many specific choices.
  • A switch statement makes the decision structure easier to read.

14. Practical Web Development Example

Imagine a student dashboard that needs to display a message based on a student’s score.

function getResult(score) {
    if (score >= 70) {
        return "Excellent performance";
    } else if (score >= 60) {
        return "Very good performance";
    } else if (score >= 50) {
        return "Good performance";
    } else if (score >= 40) {
        return "You passed";
    } else {
        return "You need to improve";
    }
}

console.log(getResult(78));

This pattern can be used in real applications such as learning management systems, dashboards, forms, quizzes and online assessments.


15. Practical Example with User Access

const userRole = "student";
const loggedIn = true;

if (!loggedIn) {
    console.log("Please log in.");
} else if (userRole === "admin") {
    console.log("Welcome, Administrator.");
} else if (userRole === "instructor") {
    console.log("Welcome, Instructor.");
} else if (userRole === "student") {
    console.log("Welcome, Student.");
} else {
    console.log("Unknown account type.");
}

This demonstrates how several conditions can be combined to control what a user sees inside a web application.


16. Practical Example with switch

const page = "courses";

switch (page) {
    case "home":
        console.log("Loading homepage...");
        break;

    case "courses":
        console.log("Loading courses...");
        break;

    case "students":
        console.log("Loading students...");
        break;

    case "contact":
        console.log("Loading contact page...");
        break;

    default:
        console.log("Page not found.");
}

This type of logic can be useful when working with navigation systems and application states.


17. Conditional Operator: A Short Alternative

For very simple two-way decisions, JavaScript also provides the ternary operator.

const age = 20;

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

console.log(message);

The general structure is:

condition ? valueIfTrue : valueIfFalse

The ternary operator is useful for short expressions, but complex decisions are usually easier to understand with normal if...else statements.


18. Common Mistakes

Mistake 1: Using = Instead of ===

// Avoid this when comparing:
if (age = 18) {
    // ...
}

The single equals sign = is an assignment operator.

For comparison, use:

if (age === 18) {
    // ...
}

Mistake 2: Forgetting Braces

Although JavaScript allows some single-statement conditions without braces, using braces consistently improves readability and reduces mistakes.

if (score >= 50) {
    console.log("Passed");
}

Mistake 3: Incorrect Condition Order

When using ranges, broad conditions placed before specific conditions may prevent later conditions from ever being reached.

Mistake 4: Forgetting break in switch

Forgetting break can cause unexpected fall-through behavior.


19. Mini Project: Student Performance Checker

Create a JavaScript program that accepts a student’s score and displays a performance message.

Requirements:

  1. Create a variable called score.
  2. If the score is 70 or above, display Excellent.
  3. If the score is between 60 and 69, display Very Good.
  4. If the score is between 50 and 59, display Good.
  5. If the score is between 40 and 49, display Pass.
  6. If the score is below 40, display Fail.

Example solution:

const score = 68;

if (score >= 70) {
    console.log("Excellent");
} else if (score >= 60) {
    console.log("Very Good");
} else if (score >= 50) {
    console.log("Good");
} else if (score >= 40) {
    console.log("Pass");
} else {
    console.log("Fail");
}

20. Why Conditional Statements Matter in Web Development

Conditional logic is one of the foundations of interactive web development.

It allows applications to respond differently depending on data or user actions.

Examples include:

  • Showing a login form when a user is not authenticated.
  • Displaying a dashboard after successful login.
  • Showing validation messages when form data is incorrect.
  • Changing content based on a user’s role.
  • Displaying different course content based on enrollment.
  • Determining whether a quiz answer is correct.
  • Showing different navigation options to different users.

Once you understand conditional statements, you can begin creating JavaScript applications that respond intelligently to different situations.


Lesson Summary

Conditional statements allow JavaScript programs to make decisions.

The if statement executes code when a condition is true. if...else provides two possible paths, while else if allows multiple conditions to be evaluated. The switch statement is useful when comparing one value against several fixed choices.

Understanding conditions, comparison operators, logical operators, truthy and falsy values, and switch statements gives you the foundation needed to build more interactive JavaScript applications.


Practice Exercise

  1. Create an if...else program that checks whether a number is positive or negative.
  2. Create a program that checks whether a user is logged in.
  3. Create a grading system using if...else if...else.
  4. Create a switch statement that displays a message for each day of the week.
  5. Create a program that checks whether a student has passed based on a score.
  6. Modify your program to display different messages for excellent, good, average and failing performance.
💻

Code Example

const studentName = "Ade";
const score = 78;
const loggedIn = true;
const role = "student";

if (!loggedIn) {
    console.log("Please log in.");
} else if (role === "admin") {
    console.log("Welcome, Administrator.");
} else if (role === "instructor") {
    console.log("Welcome, Instructor.");
} else if (role === "student") {
    console.log(`Welcome, ${studentName}.`);

    if (score >= 70) {
        console.log("Excellent performance!");
    } else if (score >= 60) {
        console.log("Very good performance.");
    } else if (score >= 50) {
        console.log("Good performance.");
    } else if (score >= 40) {
        console.log("You passed.");
    } else {
        console.log("You need to improve.");
    }
} else {
    console.log("Unknown account type.");
}

const page = "courses";

switch (page) {
    case "home":
        console.log("Loading homepage...");
        break;

    case "courses":
        console.log("Loading courses...");
        break;

    case "students":
        console.log("Loading students...");
        break;

    default:
        console.log("Page not found.");
}
⭐

Key Takeaways

["Conditional statements allow JavaScript programs to make decisions.","The if statement runs code when a condition is true.","if...else provides an alternative path when a condition is false.","else if allows multiple conditions to be checked in sequence.","Condition order matters, especially when working with ranges.","Comparison and logical operators are commonly used to build conditions.","JavaScript supports truthy and falsy values in conditional expressions.","Nested conditions are possible, but excessive nesting should be avoided.","switch is useful when comparing one expression against multiple fixed values.","break prevents unwanted switch fall-through.","default handles cases where no switch case matches.","The ternary operator provides a concise alternative for simple two-way decisions.","Conditional logic is essential for interactive websites and web applications."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress