When writing a program, there may be a situation when you need to take a path out of two given paths. Therefore, conditional statements need to be used to allow the program to make correct decisions and perform correct actions.
JavaScript supports conditional statements which are used to execute different operations based on different conditions. Here we will explain if..else statement.
JavaScript supports if..else statements in the following form:
if statement:
The if statement is a basic control statement that allows JavaScript to make decisions and execute statements conditionally.
Grammar:
if (expression){ Statement(s) to be executed if expression is true }
The JavaScript expression expression here is evaluated. If the obtained value is true, the given statement is executed. The statement will not be executed if the expression is false. Most of the time you will use comparison operations when making decisions.
Example:
<script type="text/javascript"> <!-- var age = 20; if( age > 18 ){ document.write("<b>Qualifies for driving</b>"); } //--> </script>
This will produce the following results:
Qualifies for driving
if...else statement:
The if...else statement is the next form of control statement, allowing JavaScript to execute more controllable statements.
Grammar
if (expression){ Statement(s) to be executed if expression is true }else{ Statement(s) to be executed if expression is false }
This JavaScript expression is evaluated. If the result value is true, the given statement in the if block(s), is executed. If the expression is false, the specified else statement block is executed.
Example:
<script type="text/javascript"> <!-- var age = 15; if( age > 18 ){ document.write("<b>Qualifies for driving</b>"); }else{ document.write("<b>Does not qualify for driving</b>"); } //--> </script>
This will produce the following results:
Does not qualify for driving
if...else if... Syntax:
In the form of if...else if... .control statements are advanced at one level, JavaScript sets several conditions for making correct decisions.
Grammar
if (expression 1){ Statement(s) to be executed if expression 1 is true }else if (expression 2){ Statement(s) to be executed if expression 2 is true }else if (expression 3){ Statement(s) to be executed if expression 3 is true }else{ Statement(s) to be executed if no expression is true }
There is nothing special about the code. This is simply a series of if statements, where the statement before each if is part of an else clause. The statement is executed based on the true condition, if the non-condition is true, then the else block is executed.
Example:
<script type="text/javascript"> <!-- var book = "maths"; if( book == "history" ){ document.write("<b>History Book</b>"); }else if( book == "maths" ){ document.write("<b>Maths Book</b>"); }else if( book == "economics" ){ document.write("<b>Economics Book</b>"); }else{ document.write("<b>Unknown Book</b>"); } //--> </script>
This will produce the following results:
Maths Book