If Else Statement in Javascript

  • Post category:Javascript
  • Reading time:3 mins read

In this post, We will learn the If Else Statement in Javascript using some examples.

If Else Statement in Javascript

This statement has two parts, if and else. If the value or condition that we are writing in the if is true then the if block will run.

But if the value or condition is false, then the else block will run.

if () {

}

else {

}

let color = "red";
if (color === "blue") {
  console.log("You have choosen red color");
} else {
  console.log("You have choosen blue color");
}
Output: You have choosen blue color

In the above code, I have declared a variable color with a red value. In the if statement, I used the == operator to compare the values.

If the values are not equal then the else block will run and print the result of the code written in else.

let amount = 1900;
let amountLeft = 2000 - amount;
if (amount >= 2000) {
  console.log("Thank you for purchasing the phone");
} else {
  console.log(`You need to pay $ ${total} more to buy this phone`);
}
Output: You need to pay $ 100 more to buy this phone

Let’s understand the above code.

  1. I have declared a variable amount with a value of 1900.
  2. Declared a variable amountLeft. I have subtracted the amount from 2000. So, in the amountLeft, it has a value of 100.
  3. If (1900 >= 2000) which will be false. So, if will not work in this case and it goes to the else statement. I have used template literals in the else condition.
let age = 19;
if (age == 18) {
  console.log("You are eligible to participate");
} else if (age > 18) {
  console.log("You are above 18");
} else {
  console.log("you are below 18");
}
Output: You are above 18

I have used the if, else if, and else statements.

So, in this statement, when we have written a condition for the if statement and in case it is false then it will check for the condition that we have written in the else if statement and in case it is also false then it will go to the else statement and execute the code written in this statement.

In the above code, I have declared age with a value of 19. In this case, if statement will not work as 19 is not equal to 18. else if will work as 19 is greater than 18.

Suppose, if I have declared age with 17 then in this case else statement would have worked.

Share this