DEV Community

Cover image for Conditional statement in JavaScript.
Keshav Jindal
Keshav Jindal

Posted on

Conditional statement in JavaScript.

1.Introduction
Conditions are very important topic in programming.
They are extensively used in programming as they determines a True and False condition in the code. They are of three types:

  • if condition
  • else if condition
  • else condition

NOTE
if, else if, else are the keywords and are not same as If, Else if, Else.

2.if condition
if condition determines the True condition.
Syntax

if (condition) {
 //the code block to be executed if condition is True
}
Enter fullscreen mode Exit fullscreen mode

2.1-Examples of if condition

Example 1:

const var1=10;
if (var1==10){
console.log("Its right")
Enter fullscreen mode Exit fullscreen mode

OUTPUT
"Its right".
In the above example we have declared a variable and assigned a value to it, then we checked its value through if condition.

Example 2:

if (10/2 == 5){
  console.log("Its correct")
}
Enter fullscreen mode Exit fullscreen mode

OUTPUT
"Its correct".
3.else if condition
else if condition is preceded by an if condition, and it is checked when the first if condition is not True.
3.1 Syntax

else if(condition){
//the block of code to be executed if the first if condition is  False 
}
Enter fullscreen mode Exit fullscreen mode

3.2-Examples of else if condition
Example 1:

const var1=50;
if (var1>100){
console.log("Its greater than 100")
}else if(var1>40){
console.log("Its greater than 40")
}else{
console.log("Input Invalid")
}
Enter fullscreen mode Exit fullscreen mode

OUTPUT
Its greater than 40 .
In above example, firstly if condition was checked by the machine which was False ,then machine checked else if condition which got True.
4.else condition
It is the block of code which is executed when the specified condition is False.

4.1-Syntax

else {
//code block to be executed when if condition id not True
}
Enter fullscreen mode Exit fullscreen mode

4.2-Examples of else condition
Example 1:

const num1=10;
const num2=20;
if (num1>num2){
console.log("num1 is greater than num2")
}else{
console.log("num2 is greater than num1")
}
Enter fullscreen mode Exit fullscreen mode

Example 2:

const var1=10;
if (var1 % 2 !== 0){
  console.log("Its a Even Number")
}else{
  console.log('Its a Odd Number')
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)