Conditional Statements in JavaScript: If, Else, and Switch

Programming is not just about writing lines of code. It is about making decisions. Every useful application you use daily — from login systems to shopping carts — depends on conditions. The ability of a program to choose what to do next is what makes it intelligent.

In JavaScript, conditional statements act like the brain of your program. They decide whether something should run, stop, or change direction.

Think about a traffic light.
If the light is green → cars move.
If it’s yellow → cars slow down.
If it’s red → cars stop.

JavaScript works the same way.


Why Do We Need Conditions?

Without conditions, programs would run every line of code no matter what. That would make them useless.

Imagine:

  • A login page that lets everyone in without checking the password.

  • A grading system that gives everyone an A.

  • A ticket system that charges the same price for children and seniors.

Conditions prevent that chaos.

They allow us to say:

  • If this happens → do this.

  • Otherwise → do something else.


The if Statement

The simplest conditional in JavaScript is if.

It checks a condition.
If the condition is true, the code runs.
If it is false, it skips.

Example:

let age = 18;

if (age >= 18) {
console.log("You can enter.");
}

If the age is 18 or more, the message appears.
If not, nothing happens.

Simple and powerful.


The if...else Statement

Sometimes you want two possible outcomes.

That’s where if...else comes in.

let age = 16;

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

Here, one branch must execute.
Either the if runs, or the else runs.

There is no third option.


The if...else if...else Chain

What if you have multiple conditions?

For example, grading:

let score = 85;

if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else {
console.log("Fail");
}

JavaScript checks from top to bottom.
The first true condition wins.
After that, it stops checking.

Order matters.


Comparison Operators

Conditions usually include comparison operators.

Here are the most important ones:

  • == → equal (loose comparison)

  • === → strict equal (value + type)

  • != → not equal

  • !== → strict not equal

  • < → less than

  • > → greater than

  • <= → less than or equal

  • >= → greater than or equal


Loose vs Strict Equality

This is one of the most important concepts in JavaScript.

10 == "10" // true
10 === "10" // false

Why?

Because:

  • == converts types automatically.

  • === compares value AND type.

Always prefer ===.
It avoids unexpected bugs.

Another example:

null == undefined // true
null === undefined // false

Strict comparison keeps things predictable.


Logical Operators

Sometimes one condition is not enough.
You need to combine multiple conditions.

That’s where logical operators help.

  • && → AND

  • || → OR

  • ! → NOT


AND (&&)

Both conditions must be true.

if (age > 18 && hasTicket) {
console.log("Allowed");
}

If one condition is false → result is false.


OR (||)

At least one condition must be true.

if (isAdmin || isManager) {
console.log("Access granted");
}

NOT (!)

Reverses a boolean value.

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

Parentheses help when combining logic:

if ((age > 18 && hasID) || isVIP) {
console.log("Access allowed");
}

When logic becomes too complex, it’s better to move it into a function.


The switch Statement

When you need to check exact values, switch can be cleaner than many else if statements.

Example:

let day = 2;

switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Unknown day");
}

Important:
Always use break.

Without break, JavaScript continues executing the next cases. This is called fall-through.


Common Mistakes with switch

  • Forgetting break

  • Comparing different types (42 vs "42")

  • Using switch for ranges (better use if/else)

  • Not including a meaningful default


if/else vs switch

Use if/else when:

  • You are checking ranges (score ≥ 90)

  • You have complex logic

Use switch when:

  • You are checking exact matches (day number, menu choice)

Both are correct.
The choice depends on clarity.


Practical Exercises

Let’s make things real.


1. Even or Odd Checker

function checkNumber(num) {
if (num % 2 === 0) {
return "Even";
} else {
return "Odd";
}
}

2. Age-Based Ticket System

function getTicketType(age) {
if (age < 12) {
return "Child";
} else if (age <= 59) {
return "Adult";
} else {
return "Senior";
}
}

3. Month Name Using switch

function getMonthName(monthNumber) {
switch (monthNumber) {
case 1:
return "January";
case 2:
return "February";
case 3:
return "March";
default:
return "Invalid month";
}
}

Challenge Task: Prayer Time Function

Create a function that checks prayer time based on hour:

function checkPrayerTime(hour) {
if (hour >= 4 && hour <= 6) {
return "Fajr";
} else if (hour >= 12 && hour <= 13) {
return "Dhuhr";
} else if (hour >= 15 && hour <= 16) {
return "Asr";
} else if (hour >= 18 && hour <= 19) {
return "Maghrib";
} else if (hour >= 20 && hour <= 21) {
return "Isha";
} else {
return "Not prayer time";
}
}

You can even connect it with:

let userHour = Number(prompt("Enter the hour (0–23):"));
console.log(checkPrayerTime(userHour));

        (: GOOD LUCK BUDDY                    

Comments

Popular posts from this blog

What I Learned About Linux Server Deployment (The Things No One Explains Clearly)

Understanding HTML Links, Structure, and Layout

How Python Really Handles Strings, Unicode, and Data