JavaScript Comparison and Logical Operators
Comparison and logical operators help us check if something is true
or
false
.
Comparison Operators
Comparison operators are like tools used in logical statements to figure out if things are the same or different, such as when you want to compare variables or values.
Given that x = 5
, the table below explains 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 |
How Can it be Used
You can use comparison operators in if-else statements to compare values and make decisions based on the outcome.
if (age < 18) text = "Too young to buy alcohol";
In the next part of this tutorial, you'll discover more about how to use conditional statements.
Logical Operators
Logical operators help figure out the relationship between variables or values.
When you have x = 6
and y = 3
, the table below shows how logical operators work :
Operator | Description | Example |
---|---|---|
&& | and | (x < 10 && y > 1) is true |
|| | or | (x == 5 || y == 5) is false |
! | not | !(x == y) is true |
Conditional (Ternary) Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.
Syntax
Example
If someone's age is less than 18, then the variable "voteable" will be set to "Too young." Otherwise, if the age is 18 or older, the variable "voteable" will be set to "Old enough."
Comparing Different Types
Comparing data of different types may give unexpected results.
In JavaScript, when you compare a string with a number, the language will change the string into a number before making the comparison. If the string is empty, it becomes 0. If the string is not a number, it becomes NaN, which always results in 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 you compare two strings, like '2' and '12', '2' is considered greater than '12' because in alphabetical order, '1' comes before '2'.
To get the right answer, make sure you change the type of variables to match before you compare them:
The Nullish Coalescing Operator (??)
The ??
operator gives you the first value if it's not nullish, which means it's not null
or undefined
.
Otherwise it returns the second argument.
The Optional Chaining Operator (?.)
The ?.
operator, used with an object, gives back undefined
when the object is either undefined
or null
, without causing an error.