Boolean is interesting in JavaScript, well, if you haven’t fallen into the pitfall.
true, false, and Boolean(something) (returning either of first two) are the Boolean primitive values and new Boolean(something) is the Boolean object.
When someone writes with new Boolean() in their JavaScript code and you don’t see any bugs, s/he might be
- lucky,
- having fantastic logic (kind way to say strange) in mind of coding, or
- smart or showing off or like having unnecessary code.
For me, I have never seen any scenario which requires of using Boolean object. If you have seen it, please let me know, I would like to read the code.
Here is a quick quiz for you, which ones get executed?
if (true) ...; if (Boolean(true)) ...; if (Boolean("false")) ...; if (new Boolean(false)) ...;
The answer is all of them. Take a quick look at MDN and read ToBoolean in ECMA-262.
You should have no problems with first two. Non-empty string results true and objects evaluates as true in expression. If you get third one wrong, then you probably will get wrong with
if ('true' == true) ...; // but not next one, and it's just lucky if you does get first one wrong. if ('1' == 1) ...;
First one is false, second is true. Only string and number will be converted automatically. (Hope I get this right :) This is a reason I don’t like language with such coercions, such as JavaScript or PHP, however I am not afraid of taking advantage of them. It’s just sometimes your brain has gone AWOL and you ends up with buggy code and they usually don’t expose at the moment of coding.
Moreover, this could result the abuse of === and !== usage. Either the coder is overcareful or s/he does not understand what type of the value is which just gets processed and assigned.
So, if you insist of using Boolean object, don’t forget the valueOf() method for primitive values. But hey, really?
Boolean should never be used, i guess.
ReplyDelete"!!" is your friend if you need a quick conversion from anything to boolean.^^
I kind of agree with you since I can't find any case for using Boolean other than the Boolean primitive values.
ReplyDeleteI wrote this post because I was reading some jQuery plugin code, IIRC. And it has a callback function in its options, which returns true/false for indication certain action.
Since it's a function, you will need to supply a function in order to return true/false because it has to be invoked. It's inconvenient if it's true or false in all cases.
Even though I don't use that plugin, just happen to read its code and it got me an idea. So, I was trying to see if I can make primitive value true/false to be callable, e.g. `true()`. The answer is no, but I stumbled upon Boolean on MDN. It brought me back to this again, which I was aware of and I decided I can write a little about this.