4 ms·
In Javascript - value =!!value
- milliams 13y agoDoes JavaScript not have something like "bool(value)"?
- benjoffe 13y agoYou can use Boolean(value) but it will return an 'object' of a 'boolean' type, rather than a primitive boolean (it's one of JS's flaws so is generally avoided). Note: their example of a similar piece of code is not identical, as it won't cast values like null to false. I think the best example of a clear equivalent would be: value = value ? true : false;
- gsnedders 13y ago`Boolean(value)` returns a boolean primitive; `new Boolean(value)` returns a boolean object (which you never want). Compare: > typeof Boolean(1) 'boolean' > typeof new Boolean(1) 'object'
- Guillaume86 13y agoIn chrome console I get an object for new Boolean(false) but I think it is the primitive for Boolean(false), am I right or I missed something?
- deleted 13y ago[deleted]
- onestone 13y agoThe !! mentioned in the article does exactly that.
- ars 13y agoThe edited title is very confusing because "- value = !!value" is not correct. Assuming you mean a dash and not a negative, it's still not correct. I'm sure the mods will change the title to the one from the actual post: "What the Heck is !! in JavaScript?" which is a much better title.
- ajanuary 13y agoWhile I get the arguments for not using progressive enhancement in lots of modern use cases, I'm not sure it's wise to require javascript just so the page content can spin into view.
- kibwen 13y agoThis is true in a whole slew of languages. Here's Ruby: irb(main):001:0> 3 => 3 irb(main):002:0> !3 => false irb(main):003:0> !!3 => true And here's C: #include<stdio.h> main() { printf("%d %d %d", 3, !3, !!3); // 3 0 1 } Even the venerable and (relatively) strongly-typed Python falls prey to this: >>> 3 3 >>> not 3 False >>> not not 3 True Basically any language where the ! operator coerces to boolean (or in C's case, the nearest approximation to boolean). Though personally I tend to agree that implicit coercions are undesirable, don't be too quick to cry JAVASCRIPT WUT, as it has quite a lot of precedence. :)
- xhrpost 13y agoRecently wanted to convert a string of '0' or '1' to a native boolean, shortcut value = !!~~value;
- bpicolo 13y agojsPerf shows !!parseInt(str) and parseInt(str)? true : false as being decently faster...assuming I used jsperf properly. http://jsperf.com/test-bool-cast http://jsperf.com/test-bool-cast