⚡ Rocket.net – Managed WordPress Hosting

MiltonMarketing.com  Powered by Rocket.net – Managed WordPress Hosting

Bernard Aybouts - Blog - MiltonMarketing.com

Approx. read time: 7.5 min.

Post: Learn about JavaScript IF STATEMENTS

Lesson: Understanding JavaScript IF Statements

Introduction

In JavaScript, IF statements are fundamental for controlling the flow of your program. They allow your code to make decisions based on certain conditions. By using IF statements, you can instruct the browser to perform specific actions only when particular criteria are met. This lesson will guide you through the basics of IF statements, including their syntax, usage, and various examples. By the end, you’ll also have an assignment to practice your newfound skills.


Table of Contents

  1. What is an IF Statement?
  2. Syntax of an IF Statement
  3. Comparison Operators
  4. Basic IF Statement Example
  5. Using ELSE and ELSE IF
  6. Logical Operators in IF Statements
  7. Nested IF Statements
  8. Common Pitfalls and Best Practices
  9. Assignment
  10. Answer Key

What is an IF Statement?

An IF statement is a control structure that allows your program to execute a block of code only if a specified condition is true. If the condition is false, the block of code is skipped. This mechanism is essential for making decisions within your code.

Real-World Analogy

Think of an IF statement as a simple decision-making process:

  • Condition: “Is it raining?”
    • Yes: Take an umbrella.
    • No: No need for an umbrella.

In JavaScript, the IF statement would check the condition (“Is it raining?”) and execute the appropriate action based on the result.


Syntax of an IF Statement

Understanding the syntax is crucial for writing correct IF statements. Here’s the basic structure:

Copy to Clipboard

Components:

  1. if Keyword: Initiates the IF statement.
  2. Condition: Placed within parentheses (), it’s a boolean expression that evaluates to true or false.
  3. Curly Braces : Enclose the block of code that runs if the condition is true.

Example:

Copy to Clipboard

In this example, the message will be logged only if temperature is greater than 25.


Comparison Operators

Conditions within IF statements often involve comparison operators that evaluate relationships between values. Here are the most common ones:

Operator Description Example
== Equal to (compares values after type coercion) a == b
=== Strict equal to (compares both value and type) a === b
!= Not equal to a != b
!== Strict not equal to a !== b
> Greater than a > b
< Less than a < b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b

Important Notes:

  • Type Coercion: The == and != operators perform type coercion, meaning they convert the operands to the same type before comparison. This can lead to unexpected results. For example, 5 == '5' is true.
  • Strict Equality: It’s generally recommended to use === and !== to avoid type coercion issues, ensuring both value and type match.

Basic IF Statement Example

Let’s revisit the example mentioned in your initial query, expanding it for clarity.

Example: Checking a Variable’s Value

Copy to Clipboard

Explanation:

  1. Variable Declaration: We declare a variable name and assign it the value "Angelika".
  2. IF Statement:
    • Condition: name == "Angelika" checks if the value of name is equal to "Angelika".
    • Action: If the condition is true, the browser will display an alert saying "Hello, Angelika!".

Running the Code:

If you run this script in a browser, an alert box with the message "Hello, Angelika!" will appear because the condition name == "Angelika" is true.


Using ELSE and ELSE IF

While an IF statement handles the case when a condition is true, ELSE and ELSE IF provide ways to handle alternative scenarios.

ELSE Statement

The ELSE block executes when the IF condition is false.

Copy to Clipboard

Output: "You are not eligible to vote yet." because age is 16.

ELSE IF Statement

ELSE IF allows you to check multiple conditions sequentially.

Copy to Clipboard

Output: "Grade: B" because score is 85.

Combining IF, ELSE IF, and ELSE

You can chain multiple ELSE IF statements to handle various conditions, ending with an ELSE block for all other cases.


Logical Operators in IF Statements

Logical operators allow you to combine multiple conditions within an IF statement.

Common Logical Operators:

Operator Name Description
&& Logical AND True if both conditions are true
` `
! Logical NOT Inverts the truth value of a condition

Examples:

Logical AND (&&)

Copy to Clipboard

Output: "You can drive." because both conditions are true.

Logical OR (||)

Copy to Clipboard

Output: "It's the weekend!" because day is "Saturday".

Logical NOT (!)

Copy to Clipboard

Output: "You don't need an umbrella today." because isRaining is false, and !isRaining is true.

Combining Logical Operators

You can combine multiple logical operators for more complex conditions.

Copy to Clipboard

Output: "Great day for a picnic!" because temperature > 20 and isSunny are both true, satisfying the first part of the OR condition.


Nested IF Statements

Nested IF statements are IF statements placed inside another IF statement. They allow you to check multiple layers of conditions.

Example: Nested IF

Copy to Clipboard

Explanation:

  1. First IF: Checks if user.age is at least 18.
    • True: Proceeds to the nested IF.
      • Nested IF: Checks if user.isMember is true.
        • True: Logs "Welcome, member John!"
        • False: Logs "Welcome, John! Please consider becoming a member."
    • False: Logs "Sorry, John. You must be at least 18 years old."

Output: "Welcome, member John!" because both age and isMember are true.

When to Use Nested IFs

Use nested IF statements when you need to make a decision that depends on multiple layers of conditions. However, be cautious as excessive nesting can make code harder to read and maintain. In such cases, consider using logical operators or separate functions to handle complex logic.


Common Pitfalls and Best Practices

Common Pitfalls:

  1. Missing Curly Braces :
    • Forgetting to include curly braces can lead to unexpected behavior, especially when adding more lines of code later.
Copy to Clipboard

Using Assignment Operator = Instead of Comparison == or ===:

  • Assigning a value instead of comparing can cause logical errors.
Copy to Clipboard

Type Coercion Issues:

  • Using == can lead to unexpected results due to type coercion.
Copy to Clipboard
  1. Overcomplicating Conditions:
    • Creating overly complex conditions can make code hard to read and debug.

Best Practices:

  1. Always Use Curly Braces :
    • Even for single-line statements, using curly braces enhances readability and reduces errors.
Copy to Clipboard

Prefer Strict Equality === and !==:

  • Avoid type coercion by using strict comparison operators.
Copy to Clipboard

Keep Conditions Simple:

  • Break down complex conditions into smaller, manageable parts or use helper functions.
Copy to Clipboard
  1. Use Comments to Explain Complex Logic:
    • When conditions are not self-explanatory, add comments for clarity.
  2. Consistent Formatting:
    • Maintain consistent indentation and formatting to enhance readability.

Assignment

Objective:

Apply your understanding of JavaScript IF statements by completing the following tasks. Write the code for each problem, test it to ensure it works as expected, and refer to the answer key for verification.

Problems:

  1. Basic IF Statement:
    • Create a variable score and assign it a numerical value.
    • Write an IF statement that logs "Pass" if score is 60 or above.
  2. IF-ELSE Statement:
    • Using the same score variable, write an IF-ELSE statement that logs "Pass" if score is 60 or above, and "Fail" otherwise.
  3. IF-ELSE IF-ELSE Statement:
    • Extend the previous problem by adding two more conditions:
      • If score is 90 or above, log "Excellent".
      • If score is between 75 and 89, log "Good".
  4. Using Logical Operators:
    • Create two variables, age and hasID.
    • Write an IF statement that logs "Entry Granted" only if age is 18 or above and hasID is true.
  5. Nested IF Statements:
    • Create an object user with properties isLoggedIn (boolean) and role (string).
    • Write a nested IF statement that:
      • Checks if isLoggedIn is true.
      • Inside, checks if role is "admin", then logs "Access to admin panel".
      • Else, logs "Access to user dashboard".
  6. Combining ELSE IF with Logical Operators:
    • Create a variable temperature.
    • Write an IF-ELSE IF-ELSE statement that:
      • Logs "It's cold" if temperature is below 15.
      • Logs "It's warm" if temperature is between 15 and 25.
      • Logs "It's hot" if temperature is above 25.
  7. Handling Multiple Conditions:
    • Create variables username and password.
    • Write an IF statement that logs "Login Successful" only if:
      • username is "admin".
      • password is "secure123".

Answer Key

Problem 1: Basic IF Statement

Copy to Clipboard

Explanation: If score is 60 or above, "Pass" is logged.

Problem 2: IF-ELSE Statement

Copy to Clipboard

Explanation: If score is 60 or above, "Pass" is logged; otherwise, "Fail" is logged.

Problem 3: IF-ELSE IF-ELSE Statement

Copy to Clipboard

Explanation:

  • score >= 90: "Excellent"
  • score between 75 and 89: "Good"
  • score between 60 and 74: "Pass"
  • Else: "Fail"

Problem 4: Using Logical Operators

Copy to Clipboard

Explanation: Both age is 18 or above and hasID is true must be satisfied to log "Entry Granted".

Problem 5: Nested IF Statements

Copy to Clipboard

Explanation:

  • If isLoggedIn is true:
    • If role is "admin", log "Access to admin panel".
    • Else, log "Access to user dashboard".
  • Else, prompt to log in.

Problem 6: Combining ELSE IF with Logical Operators

Copy to Clipboard

Explanation:

  • temperature < 15: "It's cold"
  • temperature between 15 and 25: "It's warm"
  • temperature > 25: "It's hot"

Problem 7: Handling Multiple Conditions

Copy to Clipboard

Explanation:

  • Both username must be "admin" and password must be "secure123" to log "Login Successful".
  • Else, log "Invalid credentials".

Conclusion

Mastering IF statements is essential for creating dynamic and responsive JavaScript applications. By understanding the syntax, comparison and logical operators, and the use of ELSE and ELSE IF blocks, you can control the flow of your programs effectively. Practice writing various IF statements and experiment with different conditions to strengthen your skills. Remember to follow best practices to write clean and maintainable code.

Happy coding!

About the Author: Bernard Aybout (Virii8)

Avatar of Bernard Aybout (Virii8)
I am a dedicated technology enthusiast with over 45 years of life experience, passionate about computers, AI, emerging technologies, and their real-world impact. As the founder of my personal blog, MiltonMarketing.com, I explore how AI, health tech, engineering, finance, and other advanced fields leverage innovation—not as a replacement for human expertise, but as a tool to enhance it. My focus is on bridging the gap between cutting-edge technology and practical applications, ensuring ethical, responsible, and transformative use across industries. MiltonMarketing.com is more than just a tech blog—it's a growing platform for expert insights. We welcome qualified writers and industry professionals from IT, AI, healthcare, engineering, HVAC, automotive, finance, and beyond to contribute their knowledge. If you have expertise to share in how AI and technology shape industries while complementing human skills, join us in driving meaningful conversations about the future of innovation. 🚀