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"
So when comparing objects it will also try to convert them.
let a = 1
let b = '1'
console.log(a == b)
// true
We can reference this table for more examples.
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" },
...
]
(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) { ... }
// 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)
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:
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!