10X Sale
kh logo
All Courses
  1. Tutorials
  2. Web Development

If…else

Updated on Sep 3, 2025
 
8,042 Views

Just like any other programming language JavaScript also have conditional statements like if…else. These conditional statements are an essential part of programming as they have logic to execute two or more different set of statements.

JavaScript supports the following form of if…else statements –

  • if statement
  • if…else statement
  • if…else if…else statement

if statement

The if statement in it’s a standalone avatar, will run a set of the statement contained inside its curly brackets to run if it evaluates to true.

var age = 22;
if(age >= 21) {
 console.log('You can vote in the election');
}
//You can vote in the election

In the above example, we initialize age to 22. Now, in the if statement we check whether age >= 21 and it is true. So, the statement 'You can vote in the election' will be printed in the console.

if..else statement

Sometimes we want to execute a set of statements if the condition checked in the if is false. This is where the variation of if statement i.e. the if…else comes into play.

var age = 18;
if(age >= 21) {
 console.log('You can vote in the election');
} else {
 console.log('You are too young to vote');
}
// You are too young to vote

We have refactored the if statement code to run the else part if the statement age >= 21, returns false. In the above example we initialize age to 18. Now, in the if statement we check whether age >= 21 and it is false. So, the statement 'You are too young to vote' will be printed in the console.

if..else if…else statement

Sometimes we need to check many set of conditions and depending on it to execute that set of statements. This is where the variation of if statement i.e. the if…else if…else comes into play. Consider the below example.

var age = 9;
if(age >= 21) {
 console.log('You can vote in the election');
} else if(age >= 15) {
 console.log('You are a teenager and cannot vote');
} else if(age >= 10) {
 console.log('You are too young to vote');
} else {
 console.log('You are still a baby');
}
// You are still a baby

We have refactored the if statement code to run two else if part and one else part. In the above example, we initialize age to 9. Now, in the if statement we check whether age >= 21 and it is false. Then we go to the next else if part and check whether age >= 15 and it is false again. Then we go to the next else if part and check whether age >= 10 and it is false again.
So, we just print the statement in else part i.e. 'You are still a baby'.

+91

By Signing up, you agree to ourTerms & Conditionsand ourPrivacy and Policy

Get your free handbook for CSM!!
Recommended Courses