Branching Statements in JavaScript


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 a 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>

To understand the flow of the if statement. Please check out the following flow chart diagram of the if statement.

if statement in JavaScript

If else Statement:

We use an if-else statement in case we want to run a piece of code if the 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>

To understand the flow of the if-else statement. Please check out the following flow chart diagram.

Branching statements in JavaScript

Else if Statement:

We use an 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>

To understand the flow of the else-if statement. Please check out the following flow chart diagram.

Branching Statements in JavaScript

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>

To understand the flow of the switch statement. Please check out the following flow chart diagram.

Branching Statements in JavaScript



Spread the love:

Please share this page on social media with your friends..

Facebook share Twitter Linkedin share