In this tutorial, we will learn about different Branching statements in JavaScript. Like other programming languages JavaScript also have Branching statements with allow us to add conditions in our Code. For Example, you want to add condition a user can only submit the form if He/She will add 10 digits in Mobile numbers. If someone is trying to provide the wrong mobile number(less than 10 digits) that would be not allowed to submit the form.

There are mainly four kinds of branching statements are available in JavaScript. These branching statements are as follow.

  • if Statement
  • if else Statement
  • else if Statement
  • switch Statement

Now we will check all these branching statements in detail.

if Statement: 

if statement we normally use when in case we want to run a piece of code if a certain condition will true otherwise not.

<script>  
var num=10;  
if(num==10){  
document.write("num is equal to 10");  
}  
</script>

if else Statement:

we use if-else statement in case we want to run a piece of code if condition inside if statement will true otherwise we will run another piece of code which we write in else block of the statement.

<script>  
var num=5;  
if(num%2==0){  
document.write("num is even number");  
}  
else{  
document.write("num is odd number");  
}  
</script>

else if Statement:

we use else if statement in case we have multiple conditions and we want to run a piece of code from the block where the condition would true.

<script>  
var marks=75;  
if(marks>=80){  
document.write("Grade A");  
}  
else if(marks>=60){  
document.write("Grade B");  
}  
else if(marks>=40){  
document.write("Grade C");  
}  
else{  
document.write("Fail");  
}  
</script>

switch Statement:

We use switch statement in case we have multiple choices.

<script>  
var num=1';  
var result;  
switch(num){  
case 1:  
document.write("Red");   
break;  
case 2:  
document.write("Green");
break;  
case 3:  
document.write("Blue");
break;  
default:  
document.write("Black"); 
}    
</script>