JavaScript Comparison
and Logical Operators
Comparison and logical operators are used to test for true or false.
Comparison Operators
Comparison operators are used in logical statements to determine equality or difference between variables or values.
Given x=5, the table below explains the comparison operators:
Operator | Description | Comparison | Return Value | Example |
---|---|---|---|---|
== | Equal to | x==8 | false | Example » |
x==5 | true | Example » | ||
=== | Exactly equal (value and type) | x==="5" | false | Example » |
x===5 | true | Example » | ||
!= | Not equal | x!=8 | true | Example » |
!== | Not exactly equal (value and type) | x!=="5" | true | Example » |
x!==5 | false | Example » | ||
> | Greater than | x>8 | false | Example » |
< | Less than | x<8 | true | Example » |
>= | Greater than or equal to | x>=8 | false | Example » |
<= | Less than or equal to | x<=8 | true | Example » |
How to Use
You can use comparison operators in conditional statements to compare values and take action based on the result:
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 table below explains the logical operators:
Operator | Description | Example | ||||
---|---|---|---|---|---|---|
&& | and | (x < 10 && y > 1) is true | ||||
or | (x==5 | y==5) is false | ||||
! | not | !(x==y) is true |
Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.
Syntax
Example
Example
If the value in the variable age is less than 18, assign "Too young" to the variable voteable, otherwise assign "Old enough".
voteable = (age < 18) ? "Too young" : "Old enough";