this post was submitted on 25 Jan 2025
1513 points (99.1% liked)
Programmer Humor
27029 readers
922 users here now
Welcome to Programmer Humor!
This is a place where you can post jokes, memes, humor, etc. related to programming!
For sharing awful code theres also Programming Horror.
Rules
- Keep content in english
- No advertisements
- Posts must be related to programming or programmer topics
founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
Why the double negation?
It's a handy way to convert any value to a Boolean. If
window.chromeis defined and done non-empty value, double negation turns it into justtrue.I've been wondering why not
window.chrome == trueorBoolean(window.chrome), but it turns out that the former doesn't work and that==has essentially no use unless you remember some completely arbitrary rules, and that JS developers would complain that the latter is too long given the fact that I've seen javascript code using!0for true and!1for false, instead of justtrueandfalsebecause they can save 2 to 3 characters that way.If you make sure the types match, like by explicitly converting things on the same line on that example, then you can use it just like if it was
===.In fact, there are people that defend that if your code behaves differently when you switch those two operators, your code is wrong. (Personally, I defend that JS it a pile of dogshit, and you should avoid going to dig there.)
I've never seen the
!0and!1, it is dumb and indicates either young or terrible devs.Boolean(window.chrome)is the best,!!window.chromeis good, no need to test if it's equal totrueif you make it a boolean beforehand.i just added the
=== truefor clarityJS "idiomatic" way to cast to boolean. But could just be written as
!window.chromeinstead.