DEV Community

Mark Tony
Mark Tony

Posted on

JS - If, else and else if Statements

Conditional Statements

JavaScript uses the conditional Statements (if,else and else if) to decide the flow of the code based on the validation of statements. The statements are the boolean values (True/False).

1. if Statement:
The if statement executes the block of code when the condition is true. Otherwise it skips it.

function calculate (){
  const leftOperand = Number (previousValue);
  const rightOperand = Number (currentValue);
  if(operator == "+") {
    currentValue = leftOperand + rightOperand;
      } 
Enter fullscreen mode Exit fullscreen mode

This if statement will execute the block of code, when the operator is + addition.

2. if else Statement:
The else statement will be executed when the if statement is false and the block of code of the else statement takes up the flow.

    <script>
let mark = 80

if(mark > 90 && mark <= 100){
  console.log("Grade O");

}</script>
Enter fullscreen mode Exit fullscreen mode

When the condition is true, the output will be

you are eligible to vote

when the conditon is false, the output will be

you are not eligible to vote

3. else if statement:

The else if statement is used to check more than one conditions. It executes the different block of code in a chain pattern.

let mark = 91

if(mark > 90 && mark <= 100){
  console.log("Grade O");

} else if (mark > 80) {
  console.log("Grade A");
} else if (mark > 70) {
  console.log("Grade B");
} else if ( mark < 40) {
  console.log("you are fail");  
} else {
  console.log("Invalid mark Entered, Please enter the mark within 100"); 
}

Enter fullscreen mode Exit fullscreen mode

Here the else if statement is used to test the different block of code for a grade validation function. The flow of code is decided based on the input.

Top comments (0)