If-else in JavaScript

If-else in JavaScript #5

If-else in JavaScript also knows as conditional statements. Which are used to perform different actions based on different conditions.

There are 3 types of conditional statements in JavaScript.

  1. if
  2. else
  3. else-if

If Statement

Syntax:

if (condition) {
     //code goes here
}

Example:

if (temperature < 5){
      message = "It's Very Cool!!";
}

Else-if Statement

Syntax:

else if (condition) {
     //code goes here
}

Example:

else if (temperature < 28){
      message = "It's Normal!!";
}

Else Statement

else statement used when other conditions (if and else-if) are false.

Syntax:

if (condition) {
     //code goes here
} else {
    //code goes here
}

Now Let’s combine these all conditional statements.

if (temperature < 5){
      message = "It's Very Cool!!";
} else if (temperature < 28){
      message = "It's Normal!!";
} else {
      message = "It's Very Hot!!";
}

This is what are the if-else in JavaScript and when to use it.

Previous Post: Operators in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like