Comparison and Logical Operators in Javascript
Prerequisites for following along
- A browser with a console (F12, go on, press it)
- Preferably some knowledge of variables from the previous articles
- A healthy distrust of
== - A llama (optional but encouraged)
Logical and comparison operators are a means of comparing data types. They’re basically the referees of Javascript. Constantly making judgement calls and occasionally getting it wrong.
So given x = 5:
| Operator | Description | How to use | Result |
|---|---|---|---|
| == | equal to | x == 8 / x == 5 / x == “5” | false / true / true |
| === | equal value and equal type | x === 8 / x === “5” | false / false |
| != | not equal | x != 8 | true |
| !== | not equal to value or type | x !== 8 / x !== 5 / x !== “5” | true / false / true |
| > | greater than | x > 8 | false |
| < | less than | x < 8 | true |
| >= | greater than or equal to | x >= 8 / x >= 5 | false / true |
| <= | less than or equal to | x <= 8 / x <= 5 | true / true |
The one thing worth noting here is the difference in comparison between double equals == and triple equals ===.
Double equals is fine for comparing values, but as an extra bit of safety it’s generally a good idea to use === where possible. Think of == as checking if two people look similar, and === as checking if they are literally the same person. One of them might let an imposter through. The other one checks passports, dental records and asks your mum’s maiden name.
5 == "5" // true (loose comparison, values match)
5 === "5" // false (strict comparison, types don't match)
Logical Operators
We’ve also got logical operators which let us combine conditions:
| Operator | Description | Example |
|---|---|---|
| && | AND | (x > 1 && x < 10) is true |
| || | OR | (x === 5 || x === 6) is true |
| ! | NOT | !(x === 5) is false |
These come in dead handy when you need to check multiple conditions at once. Which you will. Constantly. Forever. Get used to it.
const age = 25;
const hasID = true;
if (age >= 18 && hasID) {
console.log("Welcome to the pub");
} else {
console.log("Nice try");
}
Truthy and Falsy
Javascript also has this delightful concept of “truthy” and “falsy” values. Not every value is explicitly true or false, but Javascript will treat them as such when it needs to. Here are the falsy values:
false
0
"" // empty string
null
undefined
NaN
Everything else is truthy. Yes, even an empty array [] and an empty object {}. I know. I dont make the rules.
