JS IF-Else Statement

JavaScript IF-Else Statement

JavaScript If Statement

  • If statement is used to make a decision according to a given condition.
    The if statement evaluates the expression, if the value of expression is true then the instruction is executed.

Syntax:

if (expression){
   Execute statement if expression is true
}

Example:

<script type="text/javascript">
<!--
var a = 10;
if( a > 7 ){
   document.write("IF condition is fulfilled");
}
//-->
</script>

JavaScript If – Else Statement

  • If statement is used to make a decision according to a given condition.
    The if statement evaluates the expression, if the value of expression is false then the else block is executed.

Syntax:

if (expression){
   Execute statement if expression is true
} else {
   Execute statement else if expression is false
}

Example:

<script type="text/javascript">
<!--
var a = 10;
if( a > 7 ){
   document.write("IF condition is true");
} else {
   document.write("IF condition is false");
}
//-->
</script>

JavaScript If – Else – If Statement

Syntax:

if (condtion 1 ){
   Execute statement if condtion 1 is true
} else if (condtion 2 ){
   Execute statement if condtion 2 is true
} else if (condtion 3 ){
   Execute statement if condtion 3 is true
}  else {
   Execute statement if all conditions are false
}

Example:

<script type="text/javascript">
<!--
var a = "london";
if( a == "boston" ){
   document.write("Boston city");
} else if(a == "paris" ){
   document.write("Paris city");
} else if(a == "berlin" ){
   document.write("Berlin city");
} else {
   document.write("City names do not match");
}   
//-->
</script>