Back to JavaScript
2025-12-105 min read

JavaScript If Else

Learn JavaScript If Else step by step with clear examples and exercises.

Why This Matters

Understanding JavaScript's If Else statements is crucial for writing efficient and effective code, as they enable us to test conditions, make decisions based on those tests, and execute different actions accordingly. This flexibility is essential in creating dynamic web applications that respond to user interactions or external data changes. In interviews, demonstrating a strong understanding of If Else statements can set you apart from other candidates.

Prerequisites

Before diving into the core concept, it's important to have a solid foundation in JavaScript basics:

  • Understanding variables and data types such as strings, numbers, booleans, arrays, and objects
  • Familiarity with functions and control structures like loops (for, while, do-while)
  • Basic knowledge of how to write and run JavaScript code in a browser or Node.js environment using tools like the console, Visual Studio Code, or Atom

Core Concept

An If Else statement in JavaScript is used to test conditions and execute different blocks of code based on the result of that test. The basic structure looks like this:

if (condition) {
// Code to run if condition is true
} else if (otherCondition) {
// Code to run if first condition is false but second condition is true
} else {
// Code to run if neither of the conditions are true
}

Condition Testing (Expanded)

The condition in an If Else statement can be any expression that evaluates to a boolean value (true or false). Common examples include:

  • Comparisons using operators like ==, ===, !=, >, <, etc.
  • Checking the length of arrays or strings using methods like length and indexOf()
  • Testing if a variable is null, undefined, or empty using the null, undefined, or length === 0 checks

Multiple Conditions (Expanded)

You can test multiple conditions by adding additional else if blocks. The code within each block will only be executed if all previous conditions are false. This allows for more complex decision-making in your code.

if (condition1) {
// Code to run if condition1 is true
} else if (condition2) {
// Code to run if condition1 is false and condition2 is true
} else if (condition3) {
// Code to run if both condition1 and condition2 are false but condition3 is true
} else {
// Code to run if none of the conditions are true
}

Worked Example

Let's create a simple program that asks for a user's age, checks their age group, and provides an appropriate message:

// Ask the user for their age
const age = prompt("What is your age?");

// Test the user's age and provide an appropriate message
if (age < 13) {
console.log("You are a child.");
} else if (age < 20) {
console.log("You are a teenager.");
} else if (age < 65) {
console.log("You are an adult.");
} else {
console.log("You are a senior citizen.");
}

In this example, we've expanded the age groups to include teenagers and senior citizens. We also added more specific conditions for each group to make our program more accurate.

Common Mistakes

  1. Forgetting to include parentheses around the condition: In JavaScript, it's important to remember that conditions must be enclosed in parentheses. For example:
// Correct usage
if (age >= 18) { ... }

// Incorrect usage (will throw a syntax error)
if age >= 18 { ... }
  1. Confusing the assignment operator (=) with the equality operator (== or ===): The assignment operator is used to assign values to variables, while the equality operators are used to compare values. Always use === for strict equality checks.
  1. Using the == operator when comparing objects: When comparing objects in JavaScript, using the == operator can lead to unexpected results due to type coercion. Instead, use the === operator or JSON.stringify() to compare objects directly.

Common Mistakes (Expanded - Subheadings)

  • Forgetting Parentheses: Always enclose conditions in parentheses for proper syntax.
  • Mixing Up Assignment and Equality Operators: Use === for strict equality checks, and avoid using the assignment operator (=) for comparison.
  • Comparing Objects with ==: Use ===, JSON.stringify(), or a custom comparison function when comparing objects to avoid unexpected results.

Practice Questions

  1. Write an If Else statement that checks if a number is even or odd and provides an appropriate message.
  2. Create a program that asks for a user's grade point average (GPA) and provides different messages based on their academic standing (e.g., freshman, sophomore, junior, senior).
  3. Write an If Else statement that checks if a string contains the substring "JavaScript" and provides an appropriate message.
  4. Create a program that asks for a user's favorite programming language and provides different messages based on their choice (e.g., "That's a great choice!", "I'm not familiar with that language.", etc.)
  5. Write an If Else statement that checks if a number is prime and provides an appropriate message.

FAQ

  1. Why can't I use the = operator for comparing values in JavaScript?
  • Using the assignment operator (=) to compare values can lead to unexpected results due to type coercion. Always use the equality operators (==, ===) for comparison.
  1. What is the difference between the == and === operators in JavaScript?
  • The == operator performs type coercion, while the === operator does not. This means that == will convert data types before comparing values, which can lead to unexpected results. Use === for strict equality checks.
  1. Can I use If Else statements with loops in JavaScript?
  • Yes! You can use If Else statements within loops to make decisions based on the loop's current state or the values of variables within the loop. This is a powerful combination that allows for dynamic and flexible programming.
  1. What are some common mistakes to avoid when using If Else statements in JavaScript?
  • Common mistakes include forgetting parentheses, confusing assignment with equality operators, and comparing objects with ==. To avoid these mistakes, always enclose conditions in parentheses, use the correct operators for comparison, and be mindful of data types when comparing objects.
JavaScript If Else | JavaScript | XQA Learn