Conditional statements ( If - else )



While programming, we may come across many requirements where we need the application to behave differently based on different conditions. For such cases we use If-Else statements in JavaScript.

There are 3 ways we can use these statements

  • “If” statements
  • “else” statements
  • “else if” statements

Javascript Image

Let’s explore each of these in details.


1. "if" statement.

When we want the program to perform certain action only when a specific condition is satisfied or is true. We can use if statement using the below syntax:

if(condition){
    //actions
}
                    

E.g.

let age=18
if(age>=18){
	console.log(“You are an adult”)
}

                       


2. "else" statement

This is an extension to the earlier if statement. This is used when we want to extend the if statement and want the program to perform certain action if the condition given in the if statement is false.

if(condition){
	//perform this if the condition is satisfied
}else{
    //perform this if the condition is not satisfied
}

                

E.g.

let age=17
if(age>=18){
	console.log(“You are an adult”)
}else{
	console.log(“You are a kid”)
}

                   

You can try running the above script by modifying the age variable with different values such as more than 18 or less than 18 to observe the difference in output.



3. “else if” statement

If you want to you want to perform actions based on multiple conditions, you can use else-if statement in the if condition. The syntax for this is as below:

if(condition 1){
	//perform this if condition1 is satisfied
} else if(condition 2){
    //perform this if condition2 is satisfied
}else{
    //perform this if none of the above conditions satisfied
}

                      

E.g.

let age=50
if(age<18){
    console.log("You are kid")
}else if(age>=18 && age<60){
    console.log("You are adult")
}else{
    console.log("You are senior")
}
                            
                        

The conditions will be evaluated to be true to be considered as condition is satisfied or not.
I hope this tutorial was helpful…

Follow Me on Social Media

Advertisement
FREE Sales CRM Software

Fully customizable CRM Software for Freelancers and Small Businesses

Signup for Free

Sign up for DigitalOcean Cloud

Get FREE $200 credits, deploy your hobby projects for Free

DigitalOcean Referral Badge
Sign up for Hostinger Cloud or VPS plans and get upto 20% Discount