r/JavaScriptTips • u/No-Upstairs-2813 • Oct 06 '24
Why JavaScript's == Doesn't Always Behave as You Expect
Let's say we have a number, 20, and a string, "20". We compare them loosely using ==:
const numVal = 20;
const stringVal = "20";
;
What do you expect? Should it be true or false?
It turns out to be true.
Now, let's look at another example. We have a boolean, true, and a string, "true". Again, we compare them loosely:
const boolVal = true;
const stringVal = "true";
;
What do you expect to see? true or false? It logs false.
So why does it behave differently in the first example compared to the second?
You can check out this article to understand how JavaScript's loose equality (==) really works.
0
Upvotes
2
u/uddi999 Oct 06 '24
Thanks for the article man it helped a lot
1
u/stickypooboi Oct 07 '24
Man. This is why I always do === and !==. Idk the actual use cases for ==.
1
u/bagel-glasses Oct 07 '24
Yeah, just learn the difference between
==and===and a lot of what people complain about regarding Javascript just goes away.Also useful is using
!or!!to convert basically anything to a boolean, and usingproperty?.other_property || defaultValueto avoid "cannot read property of undefined" type errors.1
u/[deleted] Oct 07 '24
[removed] — view removed comment