4 ms·
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 m
by czynskee 6y ago
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.
- robocat 6y agoPersonally 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.
- pvorb 6y agoOkay, thanks. And why would it be faster? Optimizing !! in the JS engine seems trivial to me.
- franga2000 6y agoI 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.