JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS If Else


Conditional statements are a cornerstone of programming. In JavaScript, the if...else statement allows developers to execute different blocks of code based on whether a condition evaluates to true or false. Understanding how to use if...else correctly is essential for controlling the flow of your applications, handling user input, validating data, and responding to dynamic conditions.

This tutorial provides a detailed explanation of if...else, practical examples, common mistakes, best practices, and real-world applications to ensure a comprehensive understanding.

Why If Else Is Important

Conditional statements are vital because they allow your code to make decisions. Without conditionals, your program would execute the same way regardless of inputs or states, making it static and inflexible. With if...else, you can:

  • React differently to user input or system events.

  • Validate forms, inputs, or data from APIs.

  • Build interactive features in web applications.

  • Handle errors or unexpected cases gracefully.

  • Control the flow of execution in a predictable manner.

For example, a login system uses conditionals to verify whether the user has provided correct credentials, while an e-commerce site might use them to check stock availability before completing a purchase.

Basic Syntax

The basic syntax of an if...else statement in JavaScript is:

if (condition) {
  // Code to execute if the condition is true
} else if (anotherCondition) {
  // Code to execute if anotherCondition is true
} else {
  // Code to execute if none of the conditions are true
}

Example: Simple If Statement

let age = 18;

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

In this example, the message is logged only if the age variable is 18 or more.

Example: If Else Statement

let score = 45;

if (score >= 50) {
  console.log("You passed!");
} else {
  console.log("You failed.");
}

Here, if the score is 50 or more, the first block executes; otherwise, the second block runs.

Example: If Else If Else Statement

let marks = 85;

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("Fail");
}

This structure allows multiple conditions to be checked sequentially. Once a true condition is found, its block executes, and the rest are skipped.

Nested If Else

Sometimes, you may need to make decisions within decisions. This is where nested if...else statements come into play:

let temperature = 25;

if (temperature > 30) {
  console.log("It's hot outside.");
} else {
  if (temperature >= 20) {
    console.log("It's warm outside.");
  } else {
    console.log("It's cold outside.");
  }
}

Nested statements allow for more granular control, but excessive nesting can reduce readability. In such cases, consider breaking logic into functions.

Ternary Operator

For simpler conditional checks, the ternary operator provides a compact alternative:

let age = 20;
let access = age >= 18 ? "Allowed" : "Denied";
console.log(access); // Allowed

The ternary operator follows the syntax: condition ? valueIfTrue : valueIfFalse. It’s best suited for simple, concise conditions rather than complex logic.

Practical Examples

Example 1: Login Status

let isLoggedIn = true;

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

Example 2: Form Validation

let username = "";
let password = "secret";

if (username === "") {
  console.log("Username cannot be empty");
} else if (password.length < 6) {
  console.log("Password must be at least 6 characters long");
} else {
  console.log("Login successful");
}

Example 3: Time-Based Greeting

let hour = 14;

if (hour < 12) {
  console.log("Good morning!");
} else if (hour < 18) {
  console.log("Good afternoon!");
} else {
  console.log("Good evening!");
}

Example 4: Age Verification

let age = 16;

if (age >= 18) {
  console.log("Access granted");
} else {
  console.log("Access denied. You must be at least 18.");
}

Example 5: Checking Multiple Conditions

let marks = 80;
let attendance = 90;

if (marks >= 50 && attendance >= 75) {
  console.log("You are eligible for the exam");
} else {
  console.log("You are not eligible for the exam");
}

Example 6: Nested Conditions for Discounts

let totalPurchase = 1200;

if (totalPurchase >= 1000) {
  if (totalPurchase >= 2000) {
    console.log("You get a 20% discount");
  } else {
    console.log("You get a 10% discount");
  }
} else {
  console.log("No discount available");
}

Common Mistakes

  • Using assignment = instead of comparison == or ===.

  • Forgetting curly braces {} for blocks, which can lead to executing unintended statements.

  • Overcomplicating nested if...else instead of using functions or switch for clarity.

  • Not considering all possible conditions, which may leave some cases unhandled.

Best Practices

  • Prefer === and !== for strict comparison to avoid unexpected type coercion.

  • Keep conditions simple and readable.

  • Use the ternary operator for simple true/false conditions.

  • For deeply nested logic, break it into functions or consider switch statements.

  • Always handle all possible scenarios to prevent undefined behavior.

Real-World Applications

  • User authentication systems

  • Form validation and error handling

  • Calculating grades, discounts, or pricing tiers

  • Dynamic content rendering based on time, location, or user input

  • Game logic for player actions, scoring, and levels

Summary of JS If Else

The if...else statement in JavaScript is a fundamental tool for implementing conditional logic. It allows you to respond to different scenarios, validate inputs, and control the flow of your applications. By combining if, else if, and else, and using best practices like strict comparisons, proper nesting, and ternary operators, you can write dynamic, readable, and reliable code. Understanding if...else is essential for building interactive and intelligent web applications.


Practice Questions

Q1. How do you check if a number is positive using an if statement?

Q2. What message does this code print if score = 60?

if (score >= 50) {
  console.log("Pass");
} else {
  console.log("Fail");
}

Q3. How do you write an if...else if...else block to check grades A, B, or C?

Q4. What happens if no condition in if or else if is true?

Q5. Can you use comparison operators like >, <, == in an if condition?

Q6. What is the output if the if condition is false and there is no else block?

Q7. What values are considered falsy in an if statement?

Q8. How do you check if a user is logged in (e.g., isLoggedIn = true) before showing a message?

Q9. How does JavaScript handle non-boolean values in if conditions?

Q10. Write an if block to check if a string is not empty.


Try a Short Quiz.

No quizzes available.


JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top