JavaScript Comparison and Logical Operators
Comparison and logical operators are used to test true or false .
Comparison operators
Comparison operators are used in logic statements to determine whether variables or values are equal.
x=5, the following table explains the comparison operators:
Operator | Description | Comparison | return value | Try it! |
---|---|---|---|---|
== | equal | x==8 | false | Try It! |
x==5 | true | Try It! | ||
=== | Absolutely equal (both value and type are equal) | x==="5" | false | Try It! |
x===5 | true | Try It! | ||
!= | not equal to | x!=8 | true | Try It! |
!== | Not absolutely equal (one of the value and type is not equal, or both are not equal) | x!=="5" | true | Try It! |
x!==5 | false | Try It! | ||
> | more than the | x>8 | false | Try It! |
< | Less than | x<8 | true | Try It! |
>= | greater than or equal to | x>=8 | false | Try It! |
<= | less than or equal to | x<=8 | true | Try It! |
How to Use
You can use comparison operators in conditional statements to compare values, and then take actions based on the results:
if (age<18) x="Too young";
You will learn more about conditional statements in the next section of this tutorial.
Logical Operators
Logical operators are used to determine the logic between variables or values.
Given x=6 and y=3, the following table explains the logical operators:
Operator | Description | Example |
---|---|---|
&& | and | (x < 10 && y > 1) : true |
|| | or | (x==5 || y==5) : false |
! | not | !(x==y) : true |
Conditional Operator
JavaScript also contains conditional operators that assign values to variables based on certain conditions.
Grammar
variablename = (condition) ? value1 : value2
Example
If the value in the variable age is less than 18, assign the value "age too young" to the variable voteable, otherwise assign the value "age reached".
voteable=(age<18)? "Age is too young": "Age has reached";