Hacker News new | past | comments | ask | show | jobs | submit login

I sometimes use a triple negation !!! for that reason. I don‘t know if there are any drawbacks, especially if there are other people working on the code, but it worked pretty well for me so far.



That might work until there's somebody who uses double negation !! for some reason. But this might only be common in JavaScript, so YMMV.


I had to google this to see why on earth you would use double negation.

Apparently it's a way to negate and convert to boolean.


Yes, it's one of those dirty JavaScript tricks that abuse type conversion. Negation converts anything into a boolean, so if you negate that again, you get the equivalent of converting the into a bool. In standard (old) JS fashion, it's both slower and less readable, but people still (used to?) do it. Similar hacks include 1* for num->string and +"" for the opposite, along with several others that I have luckily managed to forget.


I've never had to use JavaScript, but I've done the *1 or &"" in Excel to force conversion to the desired type... yes, let's mercifully lay the veil of forgetting over this.


Considering Excel's offical way of writing a != b is a<>b, I think these kinds of hacks there can be excused :)


a<>b is the preferred syntax in SQL. I'm pretty sure a!=b works everywhere these days, but that hasn't always been the case.

(eta: didn't finish the thought - I'd assume SQL influenced Excel, since it's older.)


As I'm not keeping up with recent progress of the language, how would you do that today?


If x is your variable, you can just do Boolean(x) rather than !! to make it boolean. E.g. it will convert undefined, null, 0, "", and NaN to false.

This is a much more readable cast.


Personally I think it is a good rule to never use Boolean(x), String(x), etc.

The problem is that many developers are unaware that `const s = new String(x);` creates a string Object. It looks like a string, and acts like a string, except that in some places it is not a string: for example `typeof s` returns “object”! Same problem for Boolean, Number, etcetera. Yes casts are ok, but it is easier to just say never use the value object keywords because you can end up with very wierd bugs a long way from where the value object was created.

Another example:

    let x = new Boolean(true);
    console.log(x === true);
Gives false.


Okay, thanks. And why would it be faster? Optimizing !! in the JS engine seems trivial to me.


I suppose it would be easy and might already be in some engines, but it's still discouraged because you can't rely on that optimisation (there are many engines), it's semantically incorrect, and most importantly much less readable - especially for someone not tok familiar with the JS type system.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: