Bytes

Conditional Statements in JavaScript

Introduction

Conditional statements allow you to make decisions in your code based on whether a certain condition is true or false. This is an essential part of programming, as it enables your code to perform different actions based on different conditions. In this lesson, we'll cover the different types of conditional statements in JavaScript, along with examples of how they can be used.

Understanding Conditional Statements with the help of a story

Once upon a time, there was a little girl named Sarah who loved to bake cookies. One day, she decided to bake some cookies for her friends. She had a recipe, but she wanted to make sure she didn't forget any steps. So she wrote down a list of instructions:

  1. Preheat the oven to 350 degrees.
  2. Cream together the butter and sugar.
  3. Beat in the egg and vanilla.
  4. In a separate bowl, mix together the flour, baking powder, and salt.
  5. Gradually add the dry ingredients to the butter mixture, mixing well.
  6. Stir in the chocolate chips.
  7. Drop spoonful's of dough onto a baking sheet.
  8. Bake for 10-12 minutes, or until golden brown.

As she started to follow the recipe, Sarah realized that there was a problem. Sometimes the oven in her kitchen would take longer to heat up than other times. If she followed the recipe exactly, the cookies might not turn out right. She needed a way to check if the oven was hot enough before she put the cookies in.

That's when she remembered learning about conditional statements in her JavaScript class. She decided to use a conditional statement to check the oven temperature.

She added a new step to her recipe:

  1. Check the oven temperature. If it's below 350 degrees, wait until it's hot enough.

She wrote some code in JavaScript to represent this step:

if (ovenTemperature < 350) {
  waitUntilHot();
}

Now Sarah could be sure that the oven was hot enough before she put the cookies in. She continued following the recipe, and the cookies turned out perfectly!

This is how conditional statements work in JavaScript. They allow you to check a condition (in this case, the temperature of the oven) and perform a certain action if the condition is true (wait until the oven is hot enough). They are an essential part of programming, allowing you to write code that can make decisions based on different situations.

If Statements

An if statement allows you to execute a block of code if a specified condition evaluates to true. Otherwise, the block of code is skipped. The following is the syntax for an if statement in JavaScript:

if (condition) {
  // code to be executed if condition is true
}

The condition can be any expression that evaluates to a boolean value (true or false). If the condition is true, the code inside the curly braces will be executed. Otherwise, the code will be skipped. Here is an example of an if statement in JavaScript:

let num = 10;

if (num > 0) {
  console.log("The number is positive");
}

In this example, the condition is num > 0. Since num is equal to 10, which is greater than 0, the condition is true, and the code inside the curly braces will be executed. The output of this code will be "The number is positive".

Else Statements

An else statement is used to execute a block of code if the condition in the if statement is false. Here is the syntax of an else statement in JavaScript:

if (condition) {
  // code to be executed if condition is true
} else {
  // code to be executed if condition is false
}

If the condition in the if statement is true, the code inside the first set of curly braces will be executed. If the condition is false, the code inside the second set of curly braces will be executed. Here is an example of an if/else statement in JavaScript:

let num = -10;

if (num > 0) {
  console.log("The number is positive");
} else {
  console.log("The number is not positive");
}

In this example, the condition is num > 0. Since num is equal to -10, which is not greater than 0, the condition is false, and the code inside the else block will be executed. The output of this code will be "The number is not positive".

Else If Statements

An else if statement is used to check additional conditions after the first condition in an if statement is false. Here is the syntax of an else if statement in JavaScript:

if (condition1) {
  // code to be executed if condition1 is true
} else if (condition2) {
  // code to be executed if condition2 is true
} else {
  // code to be executed if both condition1 and condition2 are false
}

If the first condition is true, the code inside the first set of curly braces will be executed, and the code inside the else if and else blocks will be skipped. If the first condition is false, the second condition will be checked. If the second condition is true, the code inside the second set of curly braces will be executed, and the code inside the else block will be skipped. If both conditions are false, the code inside the else block will be executed. Here is an example of an if/else if/else statement in JavaScript:

let num = 0;

if (num > 0) {
  console.log("The number is positive");
} else if (num < 0) {
  console.log("The number is negative");
} else {
  console.log("The number is zero");

Nested If/Else Statements

Nested if/else statements are used when we want to check for more than one condition, and each condition has its own set of actions. In a nested if/else statement, there is an inner if/else statement within an outer if/else statement.

Here is the syntax of a nested if/else statement in JavaScript:

if (condition1) {
  // code to be executed if condition1 is true
  if (condition2) {
    // code to be executed if both condition1 and condition2 are true
  } else {
    // code to be executed if condition1 is true and condition2 is false
  }
} else {
  // code to be executed if condition1 is false
}

If condition1 is true, the code inside the first set of curly braces will be executed. If condition2 is also true, the code inside the inner set of curly braces will be executed. If condition2 is false, the code inside the else block will be executed. If condition1 is false, the code inside the else block will be executed.

Here is an example of a nested if/else statement in JavaScript:

let num = 10;

if (num > 0) {
  if (num < 100) {
    console.log("The number is between 0 and 100");
  } else {
    console.log("The number is greater than or equal to 100");
  }
} else {
  console.log("The number is less than or equal to 0");
}

In this example, the first condition checks if num is greater than 0. If it is, the second condition checks if num is less than 100. If it is, the code inside the first inner set of curly braces will be executed, and the output will be "The number is between 0 and 100". If num is greater than or equal to 100, the code inside the else block of the inner if statement will be executed, and the output will be "The number is greater than or equal to 100". If num is less than or equal to 0, the code inside the else block of the outer if statement will be executed, and the output will be "The number is less than or equal to 0".

Best Practices

  1. Keep it simple: Try to use simple conditions and limit the number of nested if/else statements to make your code more readable and easier to understand.
  2. Be consistent: Use the same type of braces, indentation, and spacing in your code to make it more readable and consistent. This will make it easier for other developers to read and understand your code.
  3. Use descriptive variable names: Use descriptive names for variables and avoid using single-letter variables to make your code more readable and self-explanatory.
  4. Avoid repetition: Use functions or loops to avoid repeating the same if/else statements throughout your code.
  5. Test your code: Test your code with different inputs and edge cases to ensure that it works as expected and handles unexpected inputs and errors correctly.

Real World Scenario Examples

  1. E-commerce website: When a customer adds items to their shopping cart, the website might use a conditional statement to check whether the cart is empty or not. If the cart is empty, the website might display a message to encourage the customer to add items to their cart. If the cart is not empty, the website might display the items and the total cost of the purchase.
  2. Weather App: A weather app might use conditional statements to display different information depending on the weather conditions. For example, if it's raining, the app might display an animation of raindrops falling on the screen. If it's sunny, the app might display an animation of a sun with a smiling face.
  3. Online Quiz: An online quiz might use conditional statements to calculate the score of a user based on their answers. For example, if the user answers a question correctly, the quiz might add a point to their score. If the user answers incorrectly, the quiz might deduct a point from their score. The quiz might also use conditional statements to determine the level of difficulty for each question based on the user's previous answers and their overall score.
  4. Traffic Lights: Traffic lights use conditional statements to control the flow of traffic. If the traffic light is green, the cars are allowed to move forward. If the traffic light is yellow, the cars are warned to slow down. If the traffic light is red, the cars must stop.

Conclusion

Conditional statements in JavaScript provide a way to make decisions and execute code based on certain conditions. The if statement is used to execute code if a condition is true, while the else statement is used to execute code if the condition is false. The else if statement allows for additional conditions to be checked and code to be executed accordingly. Understanding and effectively using conditional statements is an important skill for writing dynamic and responsive code in JavaScript.

Module 4: JavaScript Control Flow OperationsConditional Statements in JavaScript

Top Tutorials

Related Articles

AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter