Comparison operators are utilized in logical statements to assess the equality or difference between variables or values.
With x = 5, the table below outlines the comparison operators:
Operator |
Description |
Comparing |
Returns |
== |
equal to |
x == 8 |
false |
x == 5 |
true |
||
x == “5” |
true |
||
=== |
equal value and equal type |
x === 5 |
true |
x === “5” |
False |
||
!= |
not equal |
x != 8 |
True |
!== |
not equal value or not equal type |
x !== 5 |
False |
x !== “5” |
True |
||
x !== 8 |
True |
||
> |
greater than |
x > 8 |
False |
< |
less than |
x < 8 |
True |
>= |
greater than or equal to |
x >= 8 |
False |
<= |
less than or equal to |
x <= 8 |
True |
Comparison operators can be employed in conditional statements to compare values and perform actions based on the outcome.
if (age < 18) text = “Too young to buy alcohol”; |
Logical operators are used to evaluate the relationship between variables or values.
With x = 6 and y = 3, the table below describes 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 |
JavaScript includes a conditional operator that assigns a value to a variable based on a specified condition.
variablename = (condition) ? value1:value2 |
let voteable = (age < 18) ? “Too young”:“Old enough”; |
If the variable age is less than 18, the variable voteable will be assigned the value “Too young”; otherwise, it will be “Old enough.”
Comparing data of different types can lead to unexpected results.
When comparing a string with a number, JavaScript converts the string to a number for the comparison. An empty string is converted to 0, while a non-numeric string is converted to NaN, which is always treated as false.
Case |
Value |
2 < 12 |
true |
2 < “12” |
true |
2 < “John” |
false |
2 > “John” |
false |
2 == “John” |
false |
“2” < “12” |
false |
“2” > “12” |
true |
“2” == “12” |
false |
When comparing two strings, “2” is considered greater than “12” because, in alphabetical order, 1 comes before 2.
To ensure accurate results, variables should be converted to the appropriate type before comparison.
age = Number(age); if (isNaN(age)) { voteable = “Input is not a number”; } else { voteable = (age < 18) ? “Too young” : “Old enough”; } |