learn2kode.in

JavaScript Conditionals (if, else, switch)

Conditionals allow JavaScript to make decisions based on conditions. They help your code run different actions depending on different situations.

1. if Statement

Used to run code only when a condition is true.

Syntax
if (condition) {
  // code to run
}
Example
let age = 20;

if (age >= 18) {
  console.log("You can vote");
}
2. if...else Statement

If the condition is true → run first block

 If false → run the else block

let isRaining = true;

if (isRaining) {
  console.log("Take an umbrella");
} else {
  console.log("Enjoy the sunshine");
}
3. else if Statement

Used when you have multiple conditions to check.

let marks = 85;

if (marks >= 90) {
  console.log("Grade A");
} else if (marks >= 75) {
  console.log("Grade B");
} else {
  console.log("Grade C");
}
4. Nested if Statements

You can put one if inside another.

let loggedIn = true;
let isAdmin = false;

if (loggedIn) {
  if (isAdmin) {
    console.log("Welcome Admin");
  } else {
    console.log("Welcome User");
  }
}
5. Ternary Operator (Short if-else)

A shorter way to write if...else.

condition ? valueIfTrue : valueIfFalse;
Example
let age = 16;
let message = age >= 18 ? "Adult" : "Minor";
console.log(message);
6. switch Statement

Used when you want to compare a value with multiple possible cases.

switch (value) {
  case option1:
    // code
    break;

  case option2:
    // code
    break;

  default:
    // code if no match
}
Comparison Table
Conditional Use Case Example
if Run code if condition is true if (x > 10) {}
if...else Two possible outcomes x > 10 ? a : b
else if Multiple conditions else if (x > 20) {}
switch Many values for one expression switch(day) {}
Ternary Short if-else condition ? A : B
When to Use What?
Scenario Best Choice
Simple true/false if
Two outcomes if...else
Many conditions else if
Comparing one value with many cases switch
Very short decision Ternary