CS Engineering Gyan

JavaScript Conditions

A JavaScript program often needs to choose what should happen next. For example, an application may need to check whether a student has passed an examination, whether a customer is eligible for a discount, or whether a user has entered the correct password. These decisions are handled using conditional statements.

A condition is an expression whose result can be evaluated as true or false. JavaScript uses that result to decide whether a particular block of code should execute.

Conditional statements are therefore an important part of program control. They allow the same program to produce different results when the input or situation changes.


What is a Condition in JavaScript?

A condition is a logical expression that JavaScript evaluates while executing a program. The expression normally produces a Boolean result: true or false.

For example:

let age = 21;

age >= 18

The expression above becomes true because 21 is greater than or equal to 18.

Another example is:

let marks = 32;

marks >= 40

This expression becomes false because 32 is less than 40.


Why are Conditional Statements Needed?

Without conditional statements, JavaScript would execute instructions in a fixed sequence. Conditions give a program the ability to respond according to the data it receives.

For example, a result-processing program can display different messages depending on marks:

let marks = 68;

if(marks >= 40)
{
    console.log("Pass");
}

If the value of marks changes to 25, the same condition becomes false. This ability to make decisions is what makes programs dynamic and useful.


Types of Conditional Statements in JavaScript

JavaScript provides several ways to implement decision-making logic.

Statement Purpose
if Executes code when a condition is true.
if...else Chooses between two possible outcomes.
else if Checks multiple conditions in sequence.
Nested if Places one condition inside another condition.
switch Compares one expression with multiple fixed values.

JavaScript if Statement

The if statement is the simplest way to make a decision. JavaScript executes the statements inside the block only when the specified condition evaluates to true.

Syntax

if(condition)
{
    // statements to execute
}

Example: Check Minimum Age

let age = 19;

if(age >= 18)
{
    console.log("Age requirement satisfied");
}

Output

Age requirement satisfied

Because the value of age is 19, the expression age >= 18 evaluates to true.


Example: Check Whether a Number is Even

let number = 24;

if(number % 2 === 0)
{
    console.log("The number is even");
}

Output

The number is even

The modulus operator % gives the remainder after division. An even number produces a remainder of zero when divided by 2.


JavaScript if...else Statement

The if...else statement is useful when a program has two possible outcomes. One block executes when the condition is true, while another block executes when it is false.

Syntax

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

Example: Pass or Fail

let marks = 36;

if(marks >= 40)
{
    console.log("Student has passed");
}
else
{
    console.log("Student has failed");
}

Output

Student has failed

Here, 36 is less than 40, so JavaScript executes the else block.


Example: Check Login Status

let isLoggedIn = false;

if(isLoggedIn)
{
    console.log("Welcome to your account");
}
else
{
    console.log("Please log in first");
}

Output

Please log in first

This type of condition is common in websites where different content is shown depending on whether a user is logged in.


JavaScript else if Statement

When a program has more than two possible outcomes, multiple conditions can be checked using an else if ladder.

JavaScript evaluates the conditions from top to bottom. When it finds the first true condition, its associated block is executed and the remaining conditions are skipped.

Syntax

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

Example: Calculate Student Grade

let marks = 76;

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

Output

Grade A

The value 76 does not satisfy the first condition, but it satisfies marks >= 75. Therefore, JavaScript executes that block and stops checking the remaining conditions.


Important Point About else if Order

The order of conditions matters in an else if ladder. JavaScript stops at the first condition that evaluates to true.

For example, this order is appropriate:

if(marks >= 90)
{
    console.log("A+");
}
else if(marks >= 75)
{
    console.log("A");
}
else if(marks >= 60)
{
    console.log("B");
}

If a broader condition is placed first, later conditions may never get a chance to execute. Therefore, conditions should normally be arranged from the most restrictive or highest range to the lowest range when checking numerical ranges.


Nested if Statement

A nested if is an if statement placed inside another if statement. It can be useful when the second decision should only be considered after the first condition has been satisfied.

Syntax

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

Example: Course Eligibility

let age = 20;
let marks = 72;

if(age >= 18)
{
    if(marks >= 60)
    {
        console.log("Eligible for the course");
    }
}

Output

Eligible for the course

The inner condition is checked only after the age requirement has been satisfied.


Nested if with else

A nested condition can also contain an else block to provide feedback when an inner condition fails.

let age = 22;
let documentsSubmitted = false;

if(age >= 18)
{
    if(documentsSubmitted)
    {
        console.log("Application accepted");
    }
    else
    {
        console.log("Submit the required documents");
    }
}
else
{
    console.log("Age requirement not satisfied");
}

Output

Submit the required documents

Comparison Operators in Conditions

Comparison operators are frequently used to create conditions. They compare values and produce a Boolean result.

Operator Meaning Example Result
== Loose equality 5 == "5" true
=== Strict equality 5 === "5" false
!= Loose inequality 5 != 3 true
!== Strict inequality 5 !== "5" true
> Greater than 10 > 5 true
< Less than 4 < 8 true
>= Greater than or equal to 18 >= 18 true
<= Less than or equal to 10 <= 12 true

Why Prefer ===?

The === operator performs a strict comparison. It checks both the value and the data type.

console.log(10 == "10");
console.log(10 === "10");

Output

true
false

The first comparison allows type conversion, while the strict comparison requires both operands to have the same type as well as the same value. For predictable program logic, === is generally preferred when strict equality is intended.


Logical Operators in Conditions

Logical operators allow multiple conditions to be combined.

Operator Name Meaning
&& AND True when both conditions are true.
|| OR True when at least one condition is true.
! NOT Reverses a Boolean value.

Example Using AND (&&)

The AND operator is useful when all required conditions must be satisfied.

let age = 21;
let hasId = true;

if(age >= 18 && hasId)
{
    console.log("Entry allowed");
}
else
{
    console.log("Entry denied");
}

Output

Entry allowed

Example Using OR (||)

The OR operator is useful when at least one of several conditions can satisfy the requirement.

let hasEmail = false;
let hasMobile = true;

if(hasEmail || hasMobile)
{
    console.log("Contact information available");
}
else
{
    console.log("Contact information required");
}

Output

Contact information available

Example Using NOT (!)

let paymentCompleted = false;

if(!paymentCompleted)
{
    console.log("Payment is still pending");
}

Output

Payment is still pending

The NOT operator reverses the Boolean value. Since paymentCompleted is false, !paymentCompleted becomes true.


Truthy and Falsy Values

JavaScript does not require every condition to contain an explicit comparison. Values can also be evaluated directly in a conditional statement.

Some values are treated as falsy, while most other values are treated as truthy.

Common Falsy Values

Example

let username = "";

if(username)
{
    console.log("Username available");
}
else
{
    console.log("Username is empty");
}

Output

Username is empty

An empty string is falsy, so JavaScript executes the else block.


JavaScript switch Statement

The switch statement is useful when one expression needs to be compared against several fixed values. It can make such logic easier to read than a long series of equality checks.

Syntax

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

    case value2:
        // statements
        break;

    default:
        // default statements
}

Example: Select a Department

let department = "CS";

switch(department)
{
    case "CS":
        console.log("Computer Science");
        break;

    case "IT":
        console.log("Information Technology");
        break;

    case "EC":
        console.log("Electronics");
        break;

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

Output

Computer Science

Why is break Used in switch?

The break statement ends the current switch execution. Without it, JavaScript may continue into the following cases. This behavior is called fall-through.

Example

let option = 1;

switch(option)
{
    case 1:
        console.log("First option");
        break;

    case 2:
        console.log("Second option");
        break;

    default:
        console.log("Invalid option");
}

Output

First option

The break statement prevents the second case from being executed after the first case.


Using default in switch

The default block provides a fallback when none of the case values match.

let paymentMode = "Cheque";

switch(paymentMode)
{
    case "UPI":
        console.log("UPI payment selected");
        break;

    case "Card":
        console.log("Card payment selected");
        break;

    case "Cash":
        console.log("Cash payment selected");
        break;

    default:
        console.log("Unsupported payment mode");
}

Output

Unsupported payment mode

if...else vs switch

if...else switch
Suitable for conditions and ranges. Suitable for comparing one expression with fixed values.
Can use comparison and logical operators. Usually used for exact case matching.
Useful for complex decision logic. Useful for menu-like or fixed choices.
Can handle conditions such as marks >= 60. Works naturally with values such as "CS", "IT", or 1, 2, 3.

Practical Example: Discount Calculation

Conditions are frequently used in e-commerce applications. The following example calculates a discount according to the purchase amount.

let amount = 6500;
let discount;

if(amount >= 10000)
{
    discount = 20;
}
else if(amount >= 5000)
{
    discount = 10;
}
else if(amount >= 2000)
{
    discount = 5;
}
else
{
    discount = 0;
}

console.log("Discount: " + discount + "%");

Output

Discount: 10%

Because the purchase amount is 6500, the program selects the 10 percent discount category.


Practical Example: Temperature Message

let temperature = 38;

if(temperature >= 40)
{
    console.log("Very hot");
}
else if(temperature >= 30)
{
    console.log("Hot");
}
else if(temperature >= 20)
{
    console.log("Comfortable");
}
else
{
    console.log("Cool");
}

Output

Hot

Common Mistakes in JavaScript Conditions

Beginners often encounter errors because conditional expressions are small but sensitive to operators, data types, and logical structure.

Mistake Better Approach
Using = when a comparison is required. Use === for strict equality.
Putting a broad condition before a more specific condition. Arrange range-based conditions carefully.
Forgetting break in switch cases. Add break when fall-through is not intended.
Creating too many nested if statements. Consider simplifying the logic or combining conditions.
Ignoring false or unexpected input values. Test different possible inputs.
Using loose comparison without understanding type conversion. Prefer strict comparison when appropriate.

Best Practices for JavaScript Conditions


Where are JavaScript Conditions Used?

Conditional logic appears in many types of web applications. Some common examples include:


Interview Questions with Answers

1. What is a conditional statement in JavaScript?

A conditional statement controls which block of code should execute based on whether a condition is true or false. Common conditional statements include if, if...else, else if, and switch.

2. What is the purpose of the if statement?

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

let age = 20;

if(age >= 18)
{
    console.log("Adult");
}

Here, the message is printed because the condition is true.

3. What is the difference between if and if...else?

An if statement provides an action only for the true case. An if...else statement provides two possible paths: one for true and another for false.

if(marks >= 40)
{
    console.log("Pass");
}
else
{
    console.log("Fail");
}

4. What is an else if ladder?

An else if ladder is used when several conditions need to be checked. JavaScript evaluates the conditions from top to bottom and executes the first matching block.

5. What is a nested if statement?

A nested if is an if statement inside another if statement. It is useful when one decision depends on another decision.

6. What is the difference between == and ===?

The == operator performs loose equality and may convert data types before comparison. The === operator performs strict equality and checks both value and type.

console.log(5 == "5");
console.log(5 === "5");

Output:

true
false

7. What are logical operators in JavaScript?

The main logical operators are &&, ||, and !.

8. What is the switch statement?

The switch statement compares one expression against multiple case values. It is particularly useful when the possible choices are fixed values.

9. Why is break used in switch?

The break statement stops execution of the switch after a matching case. Without break, execution can continue into subsequent cases.

10. What happens when no switch case matches?

If none of the case values matches the switch expression, JavaScript executes the default block when one is provided.

11. What are truthy and falsy values?

When a value is used directly as a condition, JavaScript converts it to a Boolean context. Values such as false, 0, empty string, null, undefined, and NaN are commonly treated as falsy. Most other values are truthy.

12. Can logical operators be used inside an if statement?

Yes. Logical operators can combine multiple conditions.

let age = 25;
let hasTicket = true;

if(age >= 18 && hasTicket)
{
    console.log("Entry allowed");
}

13. When should switch be preferred over if...else?

Use switch when one expression needs to be compared with several fixed values. For ranges, complex expressions, or conditions involving different variables, an if...else structure is generally more suitable.

14. Why is condition order important in an else if ladder?

JavaScript stops checking an else if ladder after finding the first true condition. Therefore, placing a broad condition too early can prevent later conditions from being reached.

15. How can conditional code be made easier to maintain?

Use meaningful variable names, keep expressions simple, avoid unnecessary nesting, prefer strict comparisons where appropriate, and test different input scenarios.


Quick Revision

Concept Key Point
if Runs code when a condition is true.
if...else Provides two possible execution paths.
else if Checks multiple conditions sequentially.
Nested if Places one condition inside another.
&& Both conditions must be true.
|| At least one condition must be true.
! Reverses a Boolean value.
switch Compares one expression with fixed case values.
break Stops switch execution.
default Runs when no switch case matches.

Summary

JavaScript conditions allow programs to make decisions according to changing data and user actions. The if statement is useful for a single decision, while if...else provides two alternatives. An else if ladder can handle multiple conditions, and a nested if can represent dependent decisions.

Logical operators such as &&, ||, and ! help combine conditions. The switch statement provides a convenient way to compare one expression with several fixed values.

A good understanding of conditional statements is essential before moving to topics such as JavaScript loops, functions, arrays, DOM manipulation, events, and asynchronous programming.


← Previous: JavaScript Input & Output Next: JavaScript Loops →
Home Visit Our YouTube Channel