JavaScript if-else Statements

The if-else statement in Java can be used for executing the condition true and false. This statement can be used in three different forms as mentioned below;

  • If Statement
  • If else statement
  • if else if statement

If statement in Java Script

"If statement" is a very useful statement with which one can implement various lines of code as the condition becomes true or false. There are various ways with which "if statement" can be executed in the code. Under this statement, the content of the code is only executed when the expression becomes true. It acts as an identifier in the code. A specific kind of expression is mentioned in the brackets () which is the required condition to be met as true. Following is the syntax of "if statement"

If (condition)

Flowchart of JavaScript If statement

JavaScript If statement

If Else statement Java Script

Under this statement, there are several expressions which need to be checked. It can be executed as a loop. The content of code is executed only from several expressions are met.

//content to be evaluated if expression1 is true  
else if(expression2){  
//content to be evaluated if expression2 is true  
else if(expression3){  
//content to be evaluated if expression3 is true  
//content to be evaluated if no expression is true  

Example of if-else statement

Let us review a simple example of usage of if-else statement

Flowchart of JavaScript If...else statement

if-else statement
var a=20;  
document.write("a is equal to 10");  
else if(a==15){ 
document.write("a is equal to 15");
else if(a==20){  
document.write("a is equal to 20");  
 document.write("a is not equal to 10, 15 or 20");  

As per the above example we have seen how if-else statement can be used Javascript. It is highly useful for executing set of lines in a code when condition is met to be true and can be used to execute lines when the condition is not true (else).