CS Engineering Gyan

JavaScript Conditions

Conditions are one of the most important concepts in JavaScript. They allow a program to make decisions based on different situations. Instead of executing every statement one after another, JavaScript can check whether a condition is true or false and then execute the appropriate block of code.

Almost every interactive website uses conditional statements. Login systems, registration forms, shopping carts, online quizzes, search filters, payment gateways, and many other web applications depend on conditions to determine what action should be performed.

Without conditions, every JavaScript program would always produce the same output regardless of user input. Conditional statements make programs intelligent by allowing them to respond differently to different values and situations.


What are JavaScript Conditions?

A condition is an expression that evaluates to either true or false. JavaScript checks this result and decides which block of code should be executed.

For example, a website may allow a user to log in only if the entered password is correct. Similarly, an online examination portal may display a "Pass" message only when the student's marks satisfy the required criteria.

JavaScript provides several conditional statements that help developers implement decision-making logic efficiently.


Why are Conditions Important?

Conditional statements allow developers to control the flow of a program. Instead of executing every instruction, JavaScript performs actions only when specific conditions are satisfied.

Advantages of Using Conditions


Decision Making in JavaScript

Decision making means selecting one action from multiple possible actions based on a condition.

JavaScript first evaluates the condition. If the condition becomes true, one block of code executes. Otherwise, JavaScript skips that block or executes another block depending on the program logic.

This process allows websites to react intelligently to user actions and changing data.


The if Statement

The if statement is the simplest conditional statement in JavaScript. It executes a block of code only when the specified condition evaluates to true.

If the condition is false, JavaScript simply skips the block and continues executing the remaining statements.

Syntax

if(condition)
{
    // statements
}

How the if Statement Works

The working process of an if statement is simple.

  1. JavaScript evaluates the condition.
  2. If the result is true, the statements inside the braces execute.
  3. If the result is false, the statements are skipped.
  4. The remaining program continues normally.

Example 1: Checking Age

let age = 20;

if(age >= 18)
{
    document.write("Eligible to Vote");
}

Output

Eligible to Vote

Since the value of age is greater than or equal to 18, the condition becomes true and the message is displayed.


Example 2: Positive Number

let number = 15;

if(number > 0)
{
    console.log("Positive Number");
}

Output

Positive Number

Example 3: Even Number

let number = 12;

if(number % 2 == 0)
{
    document.write("Even Number");
}

Output

Even Number

The modulus operator returns the remainder after division. If the remainder is zero, the number is even.


Understanding Boolean Values

Every condition produces either a true or false value. JavaScript uses these Boolean values to decide whether a code block should execute.

Condition Result
10 > 5 true
8 < 3 false
15 == 15 true
20 != 20 false
7 >= 4 true

Comparison Operators Used in Conditions

Comparison operators compare two values and always return either true or false.

Operator Description Example
== Equal to 5 == 5
=== Strict Equal 5 === 5
!= Not Equal 5 != 3
> Greater Than 20 > 10
< Less Than 8 < 15
>= Greater Than or Equal 18 >= 18
<= Less Than or Equal 9 <= 12

Real-Life Examples of Conditions

Conditions are used everywhere in modern web applications.


Common Mistakes Beginners Make


Best Practices



JavaScript if...else Statement

The if...else statement is used when a program must choose between two possible actions. If the specified condition evaluates to true, the code inside the if block executes. Otherwise, the statements inside the else block are executed.

This is one of the most commonly used decision-making statements in JavaScript because many real-world situations require two possible outcomes.

Syntax

if(condition)
{
    // Executes if condition is true
}
else
{
    // Executes if condition is false
}

Example: Check Voting Eligibility

let age = 16;

if(age >= 18)
{
    document.write("You are eligible to vote.");
}
else
{
    document.write("You are not eligible to vote.");
}

Output

You are not eligible to vote.

Since the value of age is less than 18, JavaScript executes the else block.


Example: Check Pass or Fail

let marks = 72;

if(marks >= 40)
{
    document.write("Congratulations! You Passed.");
}
else
{
    document.write("Sorry! You Failed.");
}

Output

Congratulations! You Passed.

JavaScript else if Statement

Sometimes there are more than two possible outcomes. In such situations, JavaScript provides the else if statement.

The else if statement allows multiple conditions to be checked one after another. As soon as one condition becomes true, JavaScript executes its corresponding block and skips the remaining conditions.

Syntax

if(condition1)
{
    // Block 1
}
else if(condition2)
{
    // Block 2
}
else if(condition3)
{
    // Block 3
}
else
{
    // Default Block
}

Example: Student Grade Calculator

let marks = 81;

if(marks >= 90)
{
    document.write("Grade A+");
}
else if(marks >= 75)
{
    document.write("Grade A");
}
else if(marks >= 60)
{
    document.write("Grade B");
}
else if(marks >= 40)
{
    document.write("Grade C");
}
else
{
    document.write("Fail");
}

Output

Grade A

How else if Works

  1. JavaScript checks the first condition.
  2. If it is true, that block executes.
  3. If it is false, JavaScript checks the next condition.
  4. This process continues until one condition becomes true.
  5. If none of the conditions are true, the else block executes.

Nested if Statement

A nested if means placing one if statement inside another if statement. Nested conditions are useful when one decision depends on another decision.

Syntax

if(condition1)
{
    if(condition2)
    {
        // Statements
    }
}

Example: College Admission

let marks = 85;
let age = 18;

if(age >= 18)
{
    if(marks >= 75)
    {
        document.write("Admission Approved");
    }
}

Output

Admission Approved

Logical Operators in Conditions

Logical operators combine two or more conditions into a single expression.

Operator Name Meaning
&& AND Returns true only if both conditions are true.
|| OR Returns true if at least one condition is true.
! NOT Reverses the Boolean value.

Example Using AND Operator

let age = 22;
let citizen = true;

if(age >= 18 && citizen)
{
    document.write("Eligible to Vote");
}

Output

Eligible to Vote

Example Using OR Operator

let username = "admin";
let email = "admin@gmail.com";

if(username == "admin" || email == "admin@gmail.com")
{
    document.write("Login Successful");
}

Output

Login Successful

Truthy and Falsy Values

JavaScript automatically converts values into Boolean values while evaluating conditions.

Falsy Values

Truthy Values

All other values are generally considered truthy.


Common Errors While Using Conditions


Best Practices



JavaScript switch Statement

The switch statement is another decision-making statement in JavaScript. It is used when a program needs to compare a single value against multiple possible cases. Instead of writing many if...else if statements, the switch statement provides a cleaner and more organized solution.

The switch statement checks an expression and executes the matching case. If none of the cases match, the optional default block is executed.


Syntax of switch Statement

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

    case value2:
        // Statements
        break;

    default:
        // Statements
}

The break keyword stops the execution after the matching case is completed. Without break, JavaScript continues executing the following cases.


Example 1: Display Day Name

let day = 3;

switch(day)
{
    case 1:
        document.write("Monday");
        break;

    case 2:
        document.write("Tuesday");
        break;

    case 3:
        document.write("Wednesday");
        break;

    case 4:
        document.write("Thursday");
        break;

    case 5:
        document.write("Friday");
        break;

    default:
        document.write("Weekend");
}

Output

Wednesday

Example 2: Simple Calculator

let choice = "+";
let a = 15;
let b = 5;

switch(choice)
{
    case "+":
        document.write(a + b);
        break;

    case "-":
        document.write(a - b);
        break;

    case "*":
        document.write(a * b);
        break;

    case "/":
        document.write(a / b);
        break;

    default:
        document.write("Invalid Operator");
}

Output

20

The break Statement

The break statement immediately exits the switch block after executing the matched case. It prevents the execution of the remaining cases.

Example

let number = 2;

switch(number)
{
    case 1:
        document.write("One");
        break;

    case 2:
        document.write("Two");
        break;

    case 3:
        document.write("Three");
        break;
}

Because of the break statement, only the second case is executed.


The default Statement

The default block is executed when none of the specified cases match the given expression.

Example

let color = "Yellow";

switch(color)
{
    case "Red":
        document.write("Stop");
        break;

    case "Green":
        document.write("Go");
        break;

    default:
        document.write("Unknown Color");
}

Output

Unknown Color

Difference Between if...else and switch

if...else switch
Works with any condition. Compares one expression with multiple values.
Best for complex conditions. Best for fixed values.
Supports logical operators. Does not directly support logical expressions.
Can become lengthy. Provides cleaner code for multiple choices.
Suitable for ranges of values. Suitable for exact matching values.

When Should You Use switch?

Use the switch statement whenever a single variable needs to be compared with several fixed values.

  • Menu selection systems.
  • Language selection.
  • Calculator operations.
  • Day and month names.
  • User role identification.
  • Traffic signal systems.
  • Game menu options.

Real-World Applications of JavaScript Conditions

Conditional statements are used in almost every modern web application. They allow websites to react differently depending on user actions and data.

  • User Login Authentication
  • Online Registration Forms
  • Password Validation
  • Shopping Cart Discounts
  • Online Banking Systems
  • Exam Result Processing
  • Attendance Management
  • Weather Applications
  • Hotel Booking Systems
  • Food Ordering Websites
  • Quiz Applications
  • E-commerce Websites

Best Practices for Using Conditions

  • Write meaningful and easy-to-read conditions.
  • Use strict comparison (===) whenever possible.
  • Avoid unnecessary nested conditions.
  • Use switch only when comparing one variable with multiple fixed values.
  • Always include a default block in switch statements.
  • Test both true and false scenarios.
  • Write properly indented code.
  • Add comments where necessary.

Common Mistakes

  • Forgetting the break statement.
  • Using assignment (=) instead of comparison (== or ===).
  • Writing duplicate case values.
  • Ignoring the default block.
  • Creating deeply nested conditions.
  • Writing unreadable conditional expressions.

Interview Questions

  1. What are conditional statements in JavaScript?
  2. What is the difference between if and if...else?
  3. Explain the else if ladder.
  4. What is a nested if statement?
  5. What is the switch statement?
  6. Why is the break statement used?
  7. What happens if break is omitted?
  8. What is the purpose of the default statement?
  9. When should switch be preferred over if...else?
  10. What are logical operators in JavaScript?

Summary

JavaScript conditional statements enable programs to make decisions based on different situations. The if, if...else, else if, and switch statements help developers control program flow and create interactive web applications. Understanding these concepts is essential for building login systems, calculators, forms, games, shopping websites, and many other real-world applications. A strong understanding of conditions also prepares you for advanced JavaScript topics such as loops, functions, events, DOM manipulation, and asynchronous programming.


Home Visit Our YouTube Channel