Javascript If Else

JavaScript use a conditional statement which is used to perform different tasks according to the conditions. There are three forms of statements use in JavaScript.

  1. if Statement.
  2. if else Statement.
  3. if else if Statement.

if statement

The if statement is used in JavaScript to execute the code if the condition is true or false.
if (condition){ //   
    //content to be evaluated
}
Example:-
<!DOCTYPE html>  
<html>  
<body>  
<script>  
var x=50;  
if(x>30){  
document.write("value of x is greater than 30");  
}  
</script >  
</body>  
</html>
Output
Value of x is greater than 30

if else statement

The if else statement is use for either condition is true of false. Syntax
if(condition)  
{  
// set of statements  
}  
else  
{  
// set of statements  
}
Example
<!DOCTYPE html>  
<html>  
<body>  
<script>  
var x=20;  
if(x%2==0){  
document.write("x is even number");  
}  
else{  
document.write("a is odd number")  
}  
</script>  
</body>  
</html>
Output
X is even number

If else if

It checks the content only, if expression is true from several expressions. if else if statement is an advanced form of if else statement. Syntax
If (condition1)  
{  
Statement(s) to be executed if condition 1 is true  
}  
else if (condition 2)  
{  
Statement(s) to be executed if condition 2 is true  
}  
else if (condition 3)  
{  
Statement(s) to be executed if condition 3 is true  
}  
else  
{     
Statement(s) to be executed if no condition is true  
}
Example
<!DOCTYPE html>  
<html>  
<body>  
<script>  
var x=50;  
if (x==10){  
document.write("x is equal to 10");  
}  
else if(x==50){  
document.write("x is equal to 50");  
}  
else if(x==30){  
document.write("x is equal to 30");  
}  
else{  
document.write("a is not equal to 10, 50 or 30");  
}     
</script>  
</body>  
</html>
Output
x is equal to 50



ADVERTISEMENT
ADVERTISEMENT