Comparison and Logical Operators in Javascript

Comparison and Logical Operators in Javascript

· 3 min read
javascript fundamentals operators

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:

OperatorDescriptionHow to useResult
==equal tox == 8 / x == 5 / x == “5”false / true / true
===equal value and equal typex === 8 / x === “5”false / false
!=not equalx != 8true
!==not equal to value or typex !== 8 / x !== 5 / x !== “5”true / false / true
>greater thanx > 8false
<less thanx < 8true
>=greater than or equal tox >= 8 / x >= 5false / true
<=less than or equal tox <= 8 / x <= 5true / 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:

OperatorDescriptionExample
&&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 don’t make the rules.

I don’t make the rules

Available for rescue and re-platforming work

I take over platforms that already exist and are in trouble. Node, TypeScript, React and Laravel, mostly in regulated or high-traffic environments. If something needs rescuing, re-platforming or finishing, my full history is on the CV.

Related Posts

Call, Bind and Apply

javascript fundamentals

Three ways to tell a function what ’this’ is supposed to mean.

Javascript 101: Hoisting

javascript fundamentals

What JavaScript does with your declarations before it runs a single line.

Comments