JavaScript if else

Imagine you are writing a JavaScript program and you want to execute a block of code based on a condition. And you want if the condition you specified is true then only in that case the block of code should execute otherwise it should execute a different block of code or execute nothing. So how will you do that in JavaScript? The simple answer is: by using JavaScript if else statements!

These statements are known as conditional statements that we use for decision-making in JavaScript. The conditional statements control the flow of the program based on different conditions. In this tutorial, we will explore three different conditional statements in JavaScript.

  1. if statement
  2. if – else statement
  3. if – else if statement

With the help of these conditional statements, we can perform different actions based on various conditions.

For example, you have an online shopping web app. And you want to give 10% discount to the people who buy a product of price above 100$ from your shop. So in that case you will think and use a condition like if the user buys a product that is above 100$ then apply a 10% discount otherwise display the message “Not Eligible for Discount!” on the screen.

So, how to solve this kind of problem using JavaScript code? It’s possible using JavaScript if else. So how to work with these if-else statements in JavaScript? Fortunately, in this one tutorial, we have covered everything you need to know.

This tutorial will explain what is JavaScript if, else, and else if statements, the syntax to use them, the uses of if else in JavaScript programming, real-life code examples, their applications, and more. So, let’s begin.

JavaScript if Statement

JavaScript if Statement is a fundamental conditional statement that allows executing a block of code if the specified condition evaluates to true.

if Statement Syntax:

The basic syntax to use the If statement is the following:

JavaScript if statement syntax

Explanation:

  • In the if statement, first, we use the if keyword. Remember always that if keyword must be in lowercase. And if you use IF in uppercase or If in the capital first letter then it will cause a syntax error in JavaScript. So, always use if in lowercase.
  • Second, we specify a condition inside the parenthesis or round brackets ( ). The condition can be any expression that evaluates to a Boolean value either true or false. For example, (5 > 3) will evaluate to true, (5 < 3) will evaluate to false, or (a == b) or (age !== 18), etc. are examples of expressions. It can be any expression.
  • Then, we use curly braces { } in which we write our code statements that execute only based on if the condition evaluates to true otherwise the block of code will not execute and jump on the next statement after the if statement.

JavaScript if Statement Flow Chart

JavaScript if Flow Chart

JavaScript if Statement Code Example

The following JavaScript program is using if statement, that will check the age specified in the variable using a condition. That is, if the age is below or equal to 18 then execute the block of code which is an alert “Age must be above 18”. And after that, it will execute the next statement.

<script>
    
var Age = 16;
// if statement
if(Age <= 18){
    alert("Age must be above 18");
}
// next statement
document.write("This is the next statement");

</script>

In case if the condition is false the block of code will be skipped and the program will execute the next statements.

For example, I make a small change in the previous code in which I change the Age variable assigned value from 16 to 21. Now, the condition will evaluate to false which will as a result skipped and the next statement will execute.

<script>
// I assigned 21 to this variable
var Age = 21;
// if statement
if(Age <= 18){
    alert("Age must be above 18");
}
// next statement
document.write("This is the next statement");

</script>

The conditions mostly evaluate truthy or falsy values in JavaScript.

Using Multiple Conditions in JavaScript if Statement

Using multiple conditions in a JavaScript if statement allows you to evaluate multiple expressions or conditions simultaneously. By combining logical operators, such as && (logical AND) and || (logical OR), you can create complex conditions that need to satisfy multiple criteria.

Here’s the code example with an explanation:

const username = "admin";
const password = "password123";

if (username === "admin" && password === "password123") {
  alert("Login successful.");
} else {
  alert("Login failed. Invalid username or password.");
}

Explanation:

  1. In this scenario, we have three variables: username, and password.
  2. The if statement checks if both the username and password match the expected values (“admin” and “password123”, respectively) using the logical AND operator (&&).
  3. If both conditions in the if statement evaluates to true, the code block inside the if statement is executed.
  4. Inside the if block, the code displays a message indicating a successful login.
  5. If either the username or password condition in the if statement is false, the code moves to the else block and displays a message indicating a failed login due to an invalid username or password.

In the above code, I am using the alert() method to print the output in the alert. But you can also use the getElementById() method to print the output inside an HTML element.

Nested if in JavaScript

A nested if statement in JavaScript is an if statement that is placed inside another if statement. It allows for more complex decision-making by evaluating multiple conditions within each other.

Here’s the code example of nested if to understand it:

const isRipe = true;
const hasSweetTaste = true;

if (isRipe) {
  alert("This fruit is ripe.");

  if (hasSweetTaste) {
    alert("This fruit is ripe and has a sweet taste.");
  } else {
    alert("This fruit is ripe, but it does not have a sweet taste.");
  }
} else {
  alert("This fruit is not yet ripe.");
}

Explanation:

  1. In this scenario, we have two variables: isRipe, indicating whether the fruit is ripe or not, and hasSweetTaste, indicating whether the fruit has a sweet taste or not.
  2. The outer if statement checks if the fruit is ripe (isRipe is true). If true, it executes the code block inside the outer if statement.
  3. Inside the outer if block, the code displays a message indicating that the fruit is ripe.
  4. Within the outer if block, there is a nested if-else statement. It checks if the fruit has a sweet taste (hasSweetTaste is true). If true, it executes the code block inside the nested if statement, displaying a message that the fruit is ripe and has a sweet taste.
  5. If the fruit does not have a sweet taste, meaning the nested if condition is false, the code executes the code block inside the nested else statement, displaying a message that the fruit is ripe but does not have a sweet taste.
  6. If the initial if condition is false, indicating that the fruit is not yet ripe, the code moves to the else block and displays a message that the fruit is not yet ripe.

JavaScrip if else Statement

JavaScript if else is a conditional statement that is used to execute different blocks of code based on different conditions. The conditions are based on either true or false such as if the specified condition is true then do this otherwise execute the else block if the condition evaluates to false.

JavaScript if else is simply an extended version of the if statement. The if-else statement allows us to handle both the true and false conditions of the initial condition. You can show a block of code even if a condition is false using an else statement.

JavaScript if else Syntax

The basic syntax to use JavaScript if else statement, is given in the following:

JavaScript if else statement syntax

Explanation:

  • First, we use the if statement and the syntax are the same as we have discussed before.
  • After that, we use the else keyword which is also in lowercase. It is used to specify the else statement which is the most essential part of JavaScript if else statement. It will execute the code statements inside the else block if the condition evaluates to false.

JavaScript if else Statement Flow Chart

JavaScript if else Flow Chart

JavaScript if else Code Example

Let’s take a look a the real-life JavaScript if else example.

Example 1:

Scenario: Temperature Check using JavaScript if else statement

You are building a weather application, and you want to display a message based on the current temperature. Here we will use if else statement to do that.

<script>
    
// variable containing temperature
const temperature = 25;
// if else statement
if (temperature >= 30) {
  alert("It's a hot day!");
} else {
  alert("It's not too hot today.");
}

</script>

Explanation:

  1. We have a variable name, temperature which holds the current temperature value.
  2. The if-else statement checks if the temperature is greater than or equal to 30. If the condition evaluates to true, indicating that it’s a hot day, the code inside the if block is executed.
  3. In this case, the code displays the message “It’s a hot day!” using alert().
  4. If the condition is not met, meaning the temperature is below 30, the code moves to the else block.
  5. In the else block, the code executes the statement inside, which displays the message “It’s not too hot today.” using alert().

Example 2:

Scenario: You have an online shopping web app. And you want to give 10% discount to the people who buy a product of price above 100$ from your shop. So in that case you will think and use a condition like if the user buys a product that is above 100$ then apply a 10% discount otherwise display the message “Not Eligible for Discount!” on the screen.

const productPrice = 120;
const discountPercentage = 10;

//using if else statement
if (productPrice > 100) {
  const discountAmount = (productPrice * discountPercentage) / 100;
  const discountedPrice = productPrice - discountAmount;
  document.write(`Congratulations! You've got a ${discountPercentage}% discount. Your discounted price is $${discountedPrice}.`);
} else {
  document.write("Not Eligible for Discount!");
}

Explanation:

  1. The code begins by defining two variables: productPrice representing the price of the product and discountPercentage representing the percentage of the discount.
  2. The if-else statement checks if the productPrice is greater than 100, indicating eligibility for the discount. If true, the code block inside the if statement is executed.
  3. Inside the if block, the code calculates the discount amount by multiplying the productPrice with the discountPercentage and dividing by 100.
  4. The discounted price is then calculated by subtracting the discount amount from the original productPrice.
  5. Finally, the code displays a message using console.log(), showing the percentage of the discount and the discounted price.
  6. If the productPrice is not greater than 100, the code executes the else block, which displays the message “Not Eligible for Discount!” using console.log().

Nested if else in JavaScript

Nested if-else statements in JavaScript allow you to include one if-else statement within another. This allows for more complex decision-making, where different conditions and scenarios can be evaluated within each other.

Here’s the code example of nested if-else statements:

const age = 22;
const isStudent = true;

if (age >= 18) {
    document.write("You are eligible to purchase a ticket.");

  if (isStudent) {
    document.write("You qualify for a student discount.");
  } else {
    document.write("You do not qualify for a student discount.");
  }
} else {
    document.write("You are not eligible to purchase a ticket.");
}

Explanation:

  1. In this scenario, we have two variables: age representing the age of the person and isStudent indicating whether the person is a student or not.
  2. The first if-else statement checks if the person’s age is greater than or equal to 18. If true, it executes the code block inside the if statement.
  3. Inside the first if block, the code displays a message indicating that the person is eligible to purchase a ticket.
  4. Within the first if block, there is a nested if-else statement. It checks if the person is a student (isStudent variable). If true, it executes the code block inside the nested if statement, displaying a message that the person qualifies for a student discount.
  5. If the person is not a student, meaning the nested if condition is false, the code executes the code block inside the nested else statement, displaying a message that the person does not qualify for a student discount.
  6. If the initial if condition is false, indicating that the person’s age is below 18, the code moves to the else block and displays a message that the person is not eligible to purchase a ticket.

JavaScript ifelse if Statement

In JavaScript, if – else if is a conditional statement that evaluates multiple conditions and executes different blocks of code based on the result of these conditions. And basically, the main reason we use the if – else if statement is to specify multiple conditions.

JavaScript if – else if Syntax:

The following syntax shows how to use if – else if statement in JavaScript:

JavaScript if - else if syntax

By utilizing if-else if, you can create more complex logic by combining multiple conditions and logical operators to handle a wide range of possibilities.

Here’s the flow chart of JavaScript if – else if:

JavaScript if else if flow chart

JavaScript if – else if Example

Scenario: Grade Evaluation.

You are building a grading system for a class, and you need to determine the corresponding grade based on a student’s score.

const score = 85;

if (score >= 90) {
    document.write("Your grade is A.");
} else if (score >= 80) {
    document.write("Your grade is B.");
} else if (score >= 70) {
    document.write("Your grade is C.");
} else if (score >= 60) {
    document.write("Your grade is D.");
} else {
    document.write("Your grade is F.");
}

Explanation:

  1. In this scenario, we have a variable named score representing the student’s numerical score.
  2. The if-else if statement evaluates the value of the score variable using multiple conditions.
  3. Starting with the first condition, the code checks if the score is greater than or equal to 90. If true, the code block inside the first if statement is executed, and the message “Your grade is A.” is displayed.
  4. If the first condition is not met, the code moves to the next condition, which checks if the score is greater than or equal to 80. If true, the code block inside the first else if statement is executed, and the message “Your grade is B.” is displayed.
  5. The process continues with subsequent conditions. If none of the previous conditions are met, the code checks if the score is greater than or equal to 70, then 60.
  6. If any of the conditions evaluate to be true, the corresponding code block is executed and the respective grade message is displayed.
  7. Finally, if none of the conditions are met, indicating a score below 60, the code moves to the else block, which executes the code block inside and displays the message “Your grade is F.”

That’s it. Now you know JavaScript if else statement well. If you have any questions related to this tutorial, then just feel free to leave a comment below.

Don’t forget to help others by sharing this tutorial!