If Statements in JavaScript


TL ; DR:






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:

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:

Advanced Techniques

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

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:

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:

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: