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
}
2.1-Examples of if condition
Example 1:
const var1=10;
if (var1==10){
console.log("Its right")
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")
}
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
}
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")
}
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
}
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")
}
Example 2:
const var1=10;
if (var1 % 2 !== 0){
console.log("Its a Even Number")
}else{
console.log('Its a Odd Number')
}
Top comments (0)