How To Write Conditional Statements in JavaScript

Conditional statements are used to decide the flow of execution based on different conditions. If a condition is true, you can perform one action and if the condition is false, you can perform another action.

If statement

we can use the If statement if you want to check only a specific condition.

Syntax :

        
if (condition)
{
   //Code 
}
        
    
        
var a=20;  
var b=10;

if(a>b){  
 console.log("value of a is greater than b");  
}

// Output : "value of a is greater than b"          
    

If…Else statement

When the condition inside the if statement is false, the code associated with the else statement gets executed.

Syntax:

        
if (condition)
{
   //code to get executed when the condition is true
} else {
  //code to get executed when the 'if' condition fails
}
        
    
        
var age=20;

if (age>=18)
{
   console.log('You are Adult');
} else {
   console.log('You are not Adult');
}

// Output : "You are Adult"            
    

If…Else If…Else statement

When the first condition fails, the else-if allows the program to specify some new condition(s).

Syntax:

        
if (condition_one)
{
//code to execute if condition_one is true
} else {
//code to execute if the condition_one is false
} else if (condition_two) {
//code to execute if the condition_one fails but the condition_two is true
}
        
    
        
var time=11;
if (time < 10) {
  message = "Good morning";
} else if (time < 20) {
  message = "Good Afternoon";
} else {
  message = "Good evening";
}

console.log(message);

// Output : "Good Afternoon"        
            
    
Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top