DEV Community

Discussion on: Understanding JavaScript type conversions

Collapse
 
jamesthomson profile image
James Thomson

Great article. I couldn't stress this any more:

Use strict comparison for comparing values with different types to avoid implicit conversion to number

I'd say using strict comparison will help avoid 99% of bugs related to type.

The part on Symbol.toPrimitive I wasn't aware of. Very interesting!

Collapse
 
daniel13rady profile image
Daniel Brady • Edited

Use strict comparison for comparing values with different types to avoid implicit conversion to number

I'd say using strict comparison will help avoid 99% of bugs related to type.

Hmm, possibly πŸ€” but I'm not sure I agree with these statements.

When the input types are the same, == and === are identical; it's when the types are different that the value of having both abstract and strict comparison really shines for us as programmers.

In my head, I choose which comparison I use by answering this question: "Do I care about equality, or is equivalence good enough?"

If I care about equality of two values, then I care about the types of those values. But I think the comparison between those values is not the right place to enforce that: if possible, I should prefer to defend against unequal types earlier in my code using a strategy like the one @pixelgoo suggests:

Values received from user input will be in the string type. Convert them to number explicitly before using it further

If I do that, then not only does it give me more confidence in any comparisons I perform between the values, but when I know the types of my data it gives me some guarantees about the behavior of other operations I might perform with it.

On the other hand, there are many times where I do not care about value types, where I only care about the values' logical equivalence.

One of the most common scenarios for me is a "value presence check:" often I care about whether a variable has a value, but not necessarily what that value is; in this case, I can ask x == null ? and not have to worry about whether x is actually undefined, because as the author has pointed out, undefined == null πŸŽ‰

So, to me, when I see the strict comparison being used, I think, "Okay, this code cares about types and for some reason could not guarantee they are the same by this point." Does that make sense?

Collapse
 
antonmelnyk profile image
Anton Melnyk

Thank you, glad you discovered something new!