May 06, 2021 JavaScript
Comparison and logical operators are used to test true or false.
Comparison operators are used in logical statements to determine whether variables or values are equal.
Given
x-5, the following table explains the comparison operator:Operator | Describe | Comparison | Returns a value | Instance |
---|---|---|---|---|
== | Equals | x==8 | false | Examples . . . |
x==5 | true | Examples . . . | ||
=== | Absolutely equal (equal value and type) | x==="5" | false | Examples . . . |
x===5 | true | Examples . . . | ||
!= | Not equal to | x!=8 | true | Examples . . . |
!== | Not absolutely equal (one value and type are not equal, or both are not equal) | x!=="5" | true | Examples . . . |
x!==5 | false | Examples . . . | ||
> | Greater than | x>8 | false | Examples . . . |
< | Less than | x<8 | true | Examples . . . |
>= | Is greater than or equal to | x>=8 | false | Examples . . . |
<= | Less than or equal to | x<=8 | true | Examples . . . |
You can use a comparison operator in a conditional statement to compare values and then act on the results:
You'll learn more about conditional statements in the next section of this tutorial.
Logical operators are used to determine logic between variables or values.
Given the x-6 and y-3, the following table explains the logical operators:
Operator | describe | example |
---|---|---|
&& | and | (x <10 && y> 1) for TRUE |
|| | or | (x == 5 || y == 5) for False |
! | not | ! (x == y) for TRUE |
Tip: T he priority of the JavaScript logical operator is:! 、&& 、||。
JavaScript also contains conditional operators that assign variables based on certain conditions.
If the value in the variable age is less than 18, assign the variable voteable "too young" or "age has reached".