This content originally appeared on DEV Community and was authored by Nikita Kozlov
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 ?
This content originally appeared on DEV Community and was authored by Nikita Kozlov

Nikita Kozlov | Sciencx (2021-04-24T21:11:43+00:00) JS interview in 2 minutes / == vs ===. Retrieved from https://www.scien.cx/2021/04/24/js-interview-in-2-minutes-vs/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.