JavaScript Conditions

Learn how to use conditional statements in JavaScript to control the flow of your program.

Introduction to Conditions

Conditional statements allow you to execute different code blocks based on certain conditions.

The if Statement

Executes a block of code if a specified condition is true:


let age = 18;
if (age >= 18) {
  console.log("You are an adult.");
}
            

if...else Statement

Executes one block if the condition is true, another if it is false:


let time = 10;
if (time < 12) {
  console.log("Good morning!");
} else {
  console.log("Good afternoon!");
}
            

🔹 else if Statement

Tests multiple conditions:


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

switch Statement

Tests a variable against many values:


let day = "Monday";
switch (day) {
  case "Monday":
    console.log("Start of the week");
    break;
  case "Friday":
    console.log("Weekend is near!");
    break;
  default:
    console.log("Regular day");
}
            

Ternary Operator

A compact form of if...else:


let isLoggedIn = true;
let message = isLoggedIn ? "Welcome back!" : "Please log in.";
console.log(message);
            

Best Practices

  • Use if for simple conditions
  • Use switch for multiple discrete values
  • Keep ternary expressions short and readable

Practice Task

Write a program to check if a number is even or odd using a condition:


let number = 7;
if (number % 2 === 0) {
  console.log("Even");
} else {
  console.log("Odd");
}