Conditional Statements in JavaScript: A Complete Guide

4/13/2025

#Conditional Statements in JavaScript: A Complete Guide

Go Back

Conditional Statements in JavaScript: A Complete Guide

Conditional statements are used in JavaScript to make decisions based on certain conditions. They allow you to control the flow of your code and execute different blocks of code depending on whether conditions are true or false.

In this tutorial, we’ll explore the main types of conditional statements in JavaScript with examples.


#Conditional Statements in JavaScript: A Complete Guide

1. if Statement

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

✅ Syntax:

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

✅ Example:

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

2. if...else Statement

Executes one block of code if the condition is true, and another if it's false.

✅ Syntax:

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

✅ Example:

let isLoggedIn = false;
if (isLoggedIn) {
  console.log("Welcome back!");
} else {
  console.log("Please log in.");
}

3. if...else if...else Statement

Allows you to check multiple conditions.

✅ Syntax:

if (condition1) {
  // code block 1
} else if (condition2) {
  // code block 2
} else {
  // code block 3
}

✅ Example:

let score = 85;

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

4. Ternary Operator

A shorthand for if...else. It returns one of two values based on a condition.

✅ Syntax:

condition ? valueIfTrue : valueIfFalse;

✅ Example:

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

5. switch Statement

A cleaner alternative to many else if blocks. It evaluates an expression and matches it with a case.

✅ Syntax:

switch(expression) {
  case value1:
    // code block
    break;
  case value2:
    // code block
    break;
  default:
    // default code block
}

✅ Example:

let fruit = "apple";

switch (fruit) {
  case "banana":
    console.log("Banana is yellow.");
    break;
  case "apple":
    console.log("Apple is red.");
    break;
  default:
    console.log("Unknown fruit.");
}

6. Best Practices

  • ✅ Use if for simple conditions.

  • ✅ Use switch for multiple possible values of the same variable.

  • ✅ Avoid deeply nested if...else for better readability.

  • ✅ Use ternary operator for short, simple decisions.


Final Thoughts

Conditional statements are a core part of programming logic in JavaScript. They enable your code to make decisions, control flow, and adapt to different situations. By mastering if, else, switch, and the ternary operator, you'll be able to write more dynamic and responsive applications.

Table of content