Javascript TUTORIAL
Comparison Operators and if else
Comparison operators are used for comparing the value of the variables. In conjunction with if and else statements they make up the most important fabric of the javascript programming language. Let us take an example
|
<html> <body> <script type="text/javascript"> <!-- /* ******************************************************** Example if ...else and conditional operator ******************************************************** */ var d = new Date(); var time = d.getHours(); if (time < 10) { document.write("Good morning!"); } else { document.write("Good day!"); } //--> </script> </body> </html> |
If you run the above script it should display "good morning" or "good evening" depending upon the time when you play this code. The < ( less than) is a conditional operator.
You can try to experiment it online at the following link ( opens in a new window).
Javascript if else Example
The table below gives a list of the conditional operators.
| Operator |
Description |
Example |
== |
is equal to
|
5==8 returns false
|
=== |
is equal to (checks for both value and type) |
x=5 |
y="5" x==y returns true != |
is not equal
|
5!=8 returns true
|
> |
is greater than
|
5>8 returns false
|
< |
is less than
|
5<8 returns true |
>= |
is greater than or equal to
|
5>=8 returns false |
<= |
is less than or equal to
|
7<=8 returns true |
|
Conditional Statements
JavaScript has the following conditional statements, that are used to perform different actions for different decisions.
if else Statements
< If the condition is true one block of statements ( if) is executed, otherwise else block is executed.if (condition)
{
code to be executed; //if condition is true
}
else
{
code to be executes; // if condition is false
}
The example at the top of the page showed the if else construct.
if Statements
Use this statement if you want to execute some code only if a specified condition is true. The syntax of i f statement is as followsif (condition)
{
code to be executed; //if condition is true
}
The example below shows an if contruct.
|
<html> <body> <script type="text/javascript"> <!-- /* ******************************************************** Example Increment and Decrement operators ******************************************************** */ var d = new Date(); var time = d.getHours(); if (time < 12) { document.write("It is not past noon yet"); } document.write("Have a nice day"); //--> </script> </body> </html> |