|
| COMPARISON OPERATORS IN JAVASCRIPT
Comparison operators in javascript programming allows you to compare two values and depending on whether the comparison performed is true or not, returns a true or false. Comparison operators are usually used to compare a variable against a value or a variable against another variable. The comparison operators are: ==, !=, >, >= and <=. These are further explained with examples below:
Is equal to: ==
The == is used to check if two values are equal or not. Returns true if it is equal, false otherwise. The = cannot be used as it is an assignment operator ie. it is used to assign values to a variable.
Example:
if(name=='John')
{
alert('Hello John');
}
In the above example, variable name is checked against a value of John. If it is equal to John, then an alert message Hello John is outputted.
Is not equal to: !=
The != is used to check if values are not equal. Returns true if it is not equal, false otherwise.
Example:
if(name !='John')
{
alert('Hello whoever you are');
}
In the above example, variable name is checked against a value of John. If it is not equal to John, then an alert message 'Hello whoever you are is outputted.
Is greater than: >
The > is used to check if the left hand side is greater in value than the right hand side of >. Returns true if it is, false otherwise.
Example:
if(marks > 80)
{
alert('Bravo! You have an A');
}
In the above example, variable marks is checked to see if it is greater than 80. If variable marks is greater than 80, then an alert message Bravo! You have an A is outputted.
Is less than: <
The < is used to check if the left hand side is smaller in value than the right hand side of <. Returns true if it is, false otherwise.
Example:
if(marks < 100)
{
alert('You did not get 100');
}
In the above example, variable marks is checked to see if it is smaller in value than 100. If variable marks is smaller than 100, then an alert message You did not get 100 is outputted.
Is greater than or equal to: >=
The >= is used to check if the left hand side is greater than or equal to in value than the right hand side of >=. Returns true if it is, false otherwise.
Example:
if(marks >= 80)
{
alert('Bravo! You have an A');
}
In the above example, variable marks is checked to see if it is greater than or equal to 80. If variable marks is greater than or equal to 80, then an alert message Bravo! You have an A is outputted.
Is less than or equal to: <=
The <= is used to check if the left hand side is smaller than or equal in value than the right hand side of <=. Returns true if it is, false otherwise.
Example:
if(marks <= 100)
{
alert('Well done!');
}
In the above example, variable marks is checked to see if it is smaller than or equal to in value than 100. If variable marks is smaller than or equal to 100, then an alert message Well done! is outputted
 |
|
|