DEV Community

Cover image for JS interview in 2 minutes / == vs ===
Nick K
Nick K

Posted on

JS interview in 2 minutes / == vs ===

Question:
What is the difference between == and === operators?

Quick answer:
These are both comparison operators, but the === also compare types of operands.

Longer answer:
Javascript and basically typescript are languages with implicit type conversion. This means they try to convert variables to "proper" types when performing operations.

let a = 1
let b = '1';
console.log(a+b)
// "11"
Enter fullscreen mode Exit fullscreen mode

So when comparing objects it will also try to convert them.

let a = 1
let b = '1'
console.log(a == b)
// true
Enter fullscreen mode Exit fullscreen mode

We can reference this table for more examples.

image

Real-life example:
It turned out really hard to provide some realistic example of a real-life issue when you use == instead of ===

We can imagine a case when API returns a JSON object where some field can be in 3 states - present, missing, and null.

[
  ...
  { "username": "admin", roles: ["admin"] },
  { "username": "hacker", roles: null }, // disabled
  { "username": "user" },
  ...
]
Enter fullscreen mode Exit fullscreen mode

(It is weird, but I actually had this case myself when API returned null instead of [] if object property was empty array 🤷)

So if you will write a condition using == there will be a mistake.

// both these cases will be triggered
// since undefined == null is true
if (obj.prop == undefined) { ... }
if (obj.prop == null) { ... }
if (obj.prop) { ... }
Enter fullscreen mode Exit fullscreen mode

// yeah, this example is still a bit artificial, but if you can come up with something different, please share it in the comments 🙏


Btw I will post more fun stuff here and on Twitter let's be friends 👋

Top comments (1)

Collapse
 
samrocksc profile image
Sam Clark

So, I don't know if this will count towards your last example, but when I'm explaining this to new devs I use this:

const compare = null;
const us = undefined;
compare == us;
compare === us;
Enter fullscreen mode Exit fullscreen mode

And follow with the explanation that == has some valuable use cases if applied properly, and to never be afraid to use it if you need to confirm something is undefined or null.

I don't know! I like this article though, nice!