AlgoCademy
Lesson
Code

If Statements in JavaScript


TL ; DR:

  • if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

    let isRainy = true;
    if(isRainy) {
        console.log("I bring an umbrella");
    }
    






Full lesson:

As humans, we often make decisions based on conditions. For example, we might go through these decision-making processes during a day:

If it's rainy:
  I bring an umbrella

If I'm hungry:
  I have breakfast
  
I I'm tired:
  I take a nap

We can also tell the computer to make decisions like these in our programs.


If Statements:

if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

if(conditions) {
    // instructions
}

The keyword if tells JavaScript to execute the code inside the curly braces (where we have our JavaScript comment) only if the conditions defined in the parentheses are met.


Boolean conditions:

The conditions inside if statements are known as Boolean conditions and they may only be true or false.

If the boolean condition evaluates to true, the program executes the statements inside curly braces. If it evaluates to false, the statements will not execute.

If you check our example, you'll see that all the conditions there (it's rainy, I'm hungry and I'm tired) are Boolean conditions.

Let's turn those decisions into working code using if statements:

let isRainy = true;
if(isRainy) {
    console.log("I bring an umbrella");
}

The code above prints "I bring an umbrella" since the condition in the parentheses evaluates to true

But this code:

let amHungry = false;
if(amHungry) {
    console.log("I have breakfast");
}

prints nothing since amHungry evaluates to false.


Assignment
Follow the Coding Tutorial and let's practice with if statements!


Hint
Look at the examples above if you get stuck.


Introduction

If statements are a fundamental concept in programming that allow us to make decisions in our code. They are essential for creating dynamic and interactive applications. By using if statements, we can execute different blocks of code based on certain conditions, making our programs more flexible and responsive.

In this lesson, we will explore the basics of if statements in JavaScript, understand how they work, and see how they can be applied in various scenarios.

Understanding the Basics

Before diving into more complex examples, it's important to grasp the fundamental concepts of if statements. An if statement evaluates a condition and executes a block of code if the condition is true. If the condition is false, the code block is skipped.

Here is a simple example to illustrate this:

let isSunny = true;
if(isSunny) {
    console.log("I wear sunglasses");
}

In this example, the condition isSunny is true, so the message "I wear sunglasses" is printed to the console. If isSunny were false, nothing would be printed.

Main Concepts

Let's break down the key concepts and techniques involved in using if statements:

  • Condition: The condition is an expression that evaluates to true or false. It is placed inside the parentheses of the if statement.
  • Code Block: The code block is a set of instructions enclosed in curly braces {}. It is executed only if the condition is true.
  • Boolean Values: Conditions in if statements are typically boolean expressions, meaning they evaluate to either true or false.

Here is an example that combines these concepts:

let temperature = 30;
if(temperature > 25) {
    console.log("It's a hot day");
}

In this example, the condition temperature > 25 evaluates to true, so the message "It's a hot day" is printed to the console.

Examples and Use Cases

Let's explore some examples and real-world use cases where if statements are beneficial:

let isWeekend = true;
if(isWeekend) {
    console.log("I relax at home");
}

let score = 85;
if(score >= 60) {
    console.log("You passed the exam");
}

let isLoggedIn = false;
if(!isLoggedIn) {
    console.log("Please log in to continue");
}

In these examples, we see how if statements can be used to make decisions based on different conditions, such as whether it's the weekend, a passing exam score, or a user's login status.

Common Pitfalls and Best Practices

When working with if statements, it's important to be aware of common mistakes and follow best practices:

  • Avoid Redundant Conditions: Ensure that your conditions are necessary and not redundant. For example, avoid using conditions that always evaluate to true or false.
  • Use Clear and Descriptive Conditions: Write conditions that are clear and easy to understand. Use meaningful variable names to make your code more readable.
  • Keep Code Blocks Simple: Avoid placing too many instructions inside a single if statement. If the code block becomes too complex, consider breaking it into smaller functions.

Advanced Techniques

Once you are comfortable with basic if statements, you can explore more advanced techniques:

  • Else Statements: Use else statements to specify code that should run if the condition is false.
  • Else If Statements: Use else if statements to check multiple conditions in sequence.
  • Nesting If Statements: Place if statements inside other if statements to create more complex decision-making logic.

Here is an example that combines these advanced techniques:

let age = 20;
if(age < 13) {
    console.log("You are a child");
} else if(age < 20) {
    console.log("You are a teenager");
} else {
    console.log("You are an adult");
}

Code Implementation

Let's implement a more comprehensive example with well-commented code:

let weather = "sunny";
let temperature = 30;

// Check the weather condition
if(weather === "rainy") {
    console.log("I bring an umbrella");
} else if(weather === "sunny" && temperature > 25) {
    console.log("I wear sunglasses and a hat");
} else {
    console.log("I dress normally");
}

// Check if the user is logged in
let isLoggedIn = false;
if(!isLoggedIn) {
    console.log("Please log in to continue");
} else {
    console.log("Welcome back!");
}

In this example, we use if, else if, and else statements to handle different weather conditions and user login status.

Debugging and Testing

Debugging and testing are crucial for ensuring your if statements work correctly:

  • Use Console Logs: Add console.log statements to check the values of variables and the flow of your code.
  • Write Test Cases: Create test cases to verify that your if statements produce the expected results for different conditions.
  • Use Debugging Tools: Utilize debugging tools in your code editor or browser to step through your code and identify issues.

Here is an example of a test case:

function testWeatherCondition(weather, temperature) {
    if(weather === "rainy") {
        return "I bring an umbrella";
    } else if(weather === "sunny" && temperature > 25) {
        return "I wear sunglasses and a hat";
    } else {
        return "I dress normally";
    }
}

// Test cases
console.log(testWeatherCondition("rainy", 20)); // Expected: "I bring an umbrella"
console.log(testWeatherCondition("sunny", 30)); // Expected: "I wear sunglasses and a hat"
console.log(testWeatherCondition("cloudy", 20)); // Expected: "I dress normally"

Thinking and Problem-Solving Tips

When working with if statements, consider the following strategies:

  • Break Down Problems: Divide complex problems into smaller, manageable parts and tackle each part individually.
  • Use Flowcharts: Create flowcharts to visualize the decision-making process and the flow of your code.
  • Practice Regularly: Solve coding exercises and build small projects to reinforce your understanding of if statements.

Conclusion

In this lesson, we covered the basics of if statements in JavaScript, explored various examples and use cases, and discussed common pitfalls and best practices. Mastering if statements is essential for writing dynamic and interactive programs. Keep practicing and experimenting with different conditions to enhance your coding skills.

Additional Resources

For further reading and practice, check out the following resources: