J

JavaScript Handbook

Clean • Professional

JavaScript Conditional Statements

1 minute

JavaScript Conditional Statements – Overview

Conditional statements evaluate an expression (condition) and execute code only if the condition is true.

If the condition is false, the program can execute another block or skip execution entirely.

JavaScript provides several ways to handle conditions:

learn code with durgesh images

1. if Statement

The simplest form — executes a block of code only if the condition is true.

Syntax:

if (condition) {
  // code to execute if condition is true
}

Example:

let age = 18;

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

2. if…else Statement

Use this when you want to run one block of code if true, and another block if false.

Syntax:

if (condition) {
  // code if true
} else {
  // code if false
}

Example:

let age = 16;

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

3. if…else if…else Chain

Use when you have multiple conditions to check.

Syntax:

if (condition1) {
  // code if condition1 is true
} else if (condition2) {
  // code if condition2 is true
} else {
  // code if none of the above are true
}

Example:

let marks = 75;

if (marks >= 90) {
  console.log("Grade: A");
} else if (marks >= 75) {
  console.log("Grade: B");
} else if (marks >= 50) {
  console.log("Grade: C");
} else {
  console.log("Grade: Fail");
}

4. switch Statement

When you’re checking one variable against many possible values, switch is cleaner and more readable than multiple if…else blocks.

Syntax:

switch(expression) {
  case value1:
    // code to execute
    break;
  case value2:
    // code to execute
    break;
  default:
    // code if no match found
}

Example:

let day = 3;
let dayName;

switch(day) {
  case 1:
    dayName = "Monday";
    break;
  case 2:
    dayName = "Tuesday";
    break;
  case 3:
    dayName = "Wednesday";
    break;
  case 4:
    dayName = "Thursday";
    break;
  case 5:
    dayName = "Friday";
    break;
  case 6:
    dayName = "Saturday";
    break;
  case 7:
    dayName = "Sunday";
    break;
  default:
    dayName = "Invalid day";
}

console.log(dayName);

5. Ternary Operator (?:)

The ternary operator is a shorthand for simple if…else conditions.

It’s compact and often used for inline decisions or assignments.

Syntax:

condition ? expressionIfTrue : expressionIfFalse;

Example:

let age = 20;
let message = (age >= 18) ? "Adult" : "Minor";
console.log(message);

 

Article 0 of 0