Conditional Statements in JavaScript

Conditional Statements in JavaScript

Table of contents

No heading

No headings in the article.

In this article, I'll discuss the three (3) types of conditional statements in JavaScript. This article will explain everything in simple terms.

The conditional statements include:

  • If statement

  • else statement

  • else if statement

if statement

"if" statement is used to execute a block of code, only if the condition specified is met.

if (condition) { 
     //Execute if the condition is true
}
if (5 < 10) {
console.log("true")
}

OUTPUT: true

else statement

"else" statement checks only for two(2) conditions. If the expression in the program is true, the if condition is executed. If the expression is false, it jumps to the "else" statement.

if (condition) {
      //Execute if the condition is true
} else {
     // Execute if condition is false
}
if (3 > 5){
console.log ("true")
} else {
console.log ("false")
}

OUTPUT: false

else if statement

"else if" statement is used when there are more than 2 conditions involved.

if (condition1) {
     //Execute if the condition is true
} else if (condition2) {
    //Execute if condition1 is false and condition2 is true
} else {
   //Execute if both condition1 and condition2 are false
}
if (3 > 5) {
console.log("false")
} else if (3 == 5) {
console.log ("true")
} else {
console.log ("none is correct")
}

OUTPUT: none is correct