An Interest In:
Web News this Week
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
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 = 1let b = '1';console.log(a+b)// "11"
So when comparing objects it will also try to convert them.
let a = 1let 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 trueif (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
Original Link: https://dev.to/kozlovzxc/js-interview-in-2-minutes-vs-1f58
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To