Chapter 04 of 06

Conditional Statements

Conditional Statements

Imagine you're building a movie ticket booking website. Before allowing someone to book a ticket, you need to check their age. If they're 18 or older, they can book an adult ticket. Otherwise, they'll receive a child ticket. Or imagine creating an ATM application that checks whether a user has enough balance before allowing them to withdraw money.

In both situations, the program has to make a decision based on a condition. This is exactly where Conditional Statements come into play.

As the infographic explains, Conditional Statements help JavaScript make decisions based on conditions. Instead of executing every line of code, JavaScript first checks whether a condition is true or false and then decides which block of code should run.

Think of a traffic signal. If the light is green, vehicles move forward. If it's red, they stop. The action depends entirely on the condition. JavaScript follows the same decision-making process whenever it encounters a conditional statement.


How Conditional Statements Work

Every conditional statement follows a simple flow, which the infographic illustrates beautifully.

Condition
      ↓
Decision
      ↓
Execute Code

First, JavaScript evaluates a condition. The result of that condition is always either true or false. Based on that result, JavaScript decides which block of code should execute.

For example, imagine checking whether someone is eligible to vote.

let age = 20;

If the person's age is 18 or above, JavaScript can allow them to vote. Otherwise, it won't.

This simple idea forms the foundation of every decision-making program you'll build.


The if Statement

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

The infographic demonstrates this using the following example.

let age = 20;

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

Let's understand exactly what happens here.

First, JavaScript creates a variable named age and stores the value 20.

let age = 20;

Next, JavaScript checks the condition.

age >= 18

Since 20 is greater than 18, the condition becomes true.

Because the condition is true, JavaScript enters the curly braces and executes the code inside.

console.log("Adult");

Output:

Adult

The infographic explains this using a gate. If the condition is true, the gate opens and the code executes. If the condition is false, the gate remains closed, and JavaScript simply skips that block.

You can think of it like entering a theme park. If you have a valid ticket, the gate opens. If you don't, nothing happens because you're not allowed to enter.


The else Statement

Sometimes we don't want JavaScript to simply ignore a false condition. Instead, we want it to perform another action. That's exactly why the else statement exists.

The infographic uses this example.

let age = 15;

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

Let's walk through it.

JavaScript first checks the condition.

age >= 18

Since 15 is less than 18, the condition becomes false.

Instead of skipping everything, JavaScript moves to the else block and executes it.

console.log("Minor");

Output:

Minor

Think of a road that splits into two different directions. If the condition is true, JavaScript follows one road. If it's false, it follows the other. Only one path can be taken.


The else if Statement

Real-world programs often have more than two possible outcomes.

Suppose you're creating a grading system. A student could receive Grade A, Grade B, Grade C, or even Grade D. One if and one else aren't enough.

The infographic demonstrates this using marks.

let marks = 82;

if(marks >= 90){
    grade = "A";
}
else if(marks >= 75){
    grade = "B";
}
else{
    grade = "C";
}

Here's what happens.

JavaScript first checks:

marks >= 90

Since 82 is not greater than or equal to 90, the condition becomes false.

JavaScript then checks the next condition.

marks >= 75

This time, the condition is true.

Therefore,

grade = "B";

is executed, and JavaScript immediately stops checking the remaining conditions.

Only the first matching condition is executed.

You can imagine a security checkpoint with multiple gates. If the first gate doesn't allow entry, you move to the second one. As soon as one gate approves you, there's no need to check the remaining gates.


Nested if

Sometimes one decision depends on another decision. This is where a Nested if Statement becomes useful.

The infographic uses this example.

if(age >= 18){

    if(hasLicense){
        console.log("Drive");
    }

}

Let's understand the logic.

First, JavaScript checks whether the person's age is at least 18.

If the answer is No, it doesn't even bother checking the second condition.

If the answer is Yes, JavaScript moves to the second if statement.

Now it checks whether the person has a driving license.

If both conditions are true, the output becomes:

Drive

This is exactly how driving license verification works in real life. Being 18 years old alone isn't enough. You also need a valid driving license before you're legally allowed to drive.

Nested if statements are useful whenever one condition depends on another.


The switch Statement

Suppose you're creating a timetable application that displays different messages depending on the day of the week.

You could use many else if statements, but JavaScript provides a cleaner solution called the switch statement.

The infographic uses this example.

switch(day){

case "Monday":
    console.log("Start");
    break;

case "Tuesday":
    console.log("Learn");
    break;

default:
    console.log("Other Day");

}

Imagine the value of day is:

day = "Tuesday";

JavaScript begins checking each case.

Is it Monday?

No.

Is it Tuesday?

Yes.

So JavaScript executes:

console.log("Learn");

Output:

Learn

Immediately after that, it reaches:

break;

The break statement tells JavaScript to stop checking any further cases.

If none of the cases match, JavaScript executes the default block, which works similarly to an else statement.

Think of a vending machine. You press Button 1 for Coffee, Button 2 for Tea, and Button 3 for Juice. The machine checks which button you pressed and gives you the matching item.

That's exactly how a switch statement works.


Truthy and Falsy Values

One of JavaScript's most interesting features is that conditions don't always have to be written as true or false.

JavaScript automatically decides whether a value behaves like true or false.

These values are known as Truthy and Falsy values.

The infographic lists several examples.

Truthy Values

These values behave as true inside a condition.

"Hello"
1
[]
{}
Infinity
"0"

Even an empty array

[]

and an empty object

{}

are considered Truthy.


Falsy Values

These values behave as false.

false
0
""
null
undefined
NaN

These are the main Falsy values you'll encounter while programming in JavaScript.


Example of Truthy and Falsy

The infographic demonstrates this example.

if(userName){
    console.log("Welcome");
}

Suppose:

let userName = "Alex";

Since "Alex" is a Truthy value, JavaScript executes the code.

Output:

Welcome

Now imagine:

let userName = "";

An empty string is a Falsy value.

This time, JavaScript skips the code inside the if block.

This feature makes your code shorter and cleaner.

Instead of writing:

if(userName !== ""){

developers usually write:

if(userName){

because JavaScript already understands whether the value is Truthy or Falsy.


When Should You Use Each Conditional Statement?

Choosing the right conditional statement makes your code easier to read and maintain.

Use an if statement when you have only one condition to check.

Use if...else when there are exactly two possible outcomes.

Use else if when you need to evaluate multiple conditions one after another.

Use a Nested if when one condition depends on another.

Use a switch statement when you're comparing a single value against many fixed options like days, months, menu choices, or user roles.


Common Beginner Mistakes

One of the most common mistakes beginners make is using the assignment operator (=) instead of a comparison operator.

Incorrect:

if(age = 18)

Here, JavaScript assigns the value 18 instead of comparing it.

The correct approach is:

if(age === 18)

Another common mistake is forgetting the break statement inside a switch. Without break, JavaScript continues executing the remaining cases even if one case has already matched. This behavior is called fall-through and often leads to unexpected results.

Finally, many beginners create deeply nested if statements that make the code difficult to read. Whenever possible, combine conditions using logical operators such as && and || to keep your code clean and maintainable.


Real-World Applications

Conditional statements are used everywhere in modern software.

Netflix checks whether your subscription is active before playing a movie.

Amazon verifies whether a product is in stock before allowing you to place an order.

Google Maps decides whether to recommend a faster route based on current traffic conditions.

Instagram checks whether you're logged in before showing your feed.

Online banking applications verify your PIN before allowing transactions.

Every one of these applications depends on conditional statements to make intelligent decisions.


Quick Revision

Statement

Purpose

if

Executes code only when a condition is true.

else

Executes an alternative block when the condition is false.

else if

Checks multiple conditions until one matches.

Nested if

Executes one decision inside another decision.

switch

Compares one value against multiple fixed cases.

break

Stops execution after a matching switch case.

default

Executes when no switch case matches.

Truthy Values

Values treated as true, such as non-empty strings, non-zero numbers, arrays, and objects.

Falsy Values

false, 0, "", null, undefined, and NaN.

Best Practice

Use switch for fixed choices, prefer === for comparisons, and keep conditional logic simple and readable.