Conditions | Dataplexa

Conditional Statements

In real life, we make decisions all the time. If it rains, we carry an umbrella. If we have enough balance, we place an order.

JavaScript also needs to make decisions. Conditional statements allow JavaScript to run different code based on different conditions.


What Is a Conditional Statement?

A conditional statement checks a condition and decides which block of code should run.

Conditions usually return a boolean value — true or false.


The if Statement

The if statement runs code only when a condition is true.


let age = 18;

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

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


The else Statement

The else block runs when the if condition is false.


let balance = 100;

if (balance > 0) {
  console.log("Order placed");
} else {
  console.log("Insufficient balance");
}
  

This is commonly used in real-world validations.


The else if Statement

When there are multiple conditions, we use else if.


let score = 75;

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

JavaScript checks conditions from top to bottom and runs the first matching block.


Real-World Example

Imagine checking user access on a website:


let isLoggedIn = true;
let isAdmin = false;

if (isLoggedIn && isAdmin) {
  console.log("Admin dashboard");
} else if (isLoggedIn) {
  console.log("User dashboard");
} else {
  console.log("Please log in");
}
  

This logic is used in almost every web application.


Thumb Rules

  • Conditions must evaluate to true or false
  • Use === for reliable comparisons
  • Order conditions from most specific to general
  • Readable conditions are better than complex ones

More on Conditions Later

In this lesson, we focused on basic decision making using conditional statements.

More advanced conditional logic will be covered in later lessons.


What Comes Next?

Now that you know how JavaScript makes decisions, it’s time to repeat actions efficiently.

In the next lesson, we will learn about loops.