What's the point of the Boolean object?
Because this is (somewhat sadly) how the language was defined -- I suspect it was originally for performance/optimization; note the case of assignment to a string
property below. (Java works similarly, although Scala and Python largely reject this distinction).
Note that Boolean
isn't the only "wrapper type". There are also String
and Number
, for instance.
Because of this there remains a number of quirks (the below could just as much apply to Boolean):
typeof("foo") // string
typeof(new String("foo")) // object
"foo" instanceof String // false
new String("foo") instanceof String // true
// result is undefined: a string is a primitive and silently "ate" the assignment
// this also makes it a much cheaper value as it's not a "real" object
x = "f"; x.bar = 42; x.bar
// result is 42: a String is a "real" object with real properties!
// however, this also means that it may have a good bit more overhead
x = new String("f"); x.bar = 42; x.bar
I know this didn't "answer" the question, but rather chucks some more wood on the fire ;-)
The only real "gotcha" otherwise from the above is that perhaps new Boolean(false)
is a truth-y value.
Happy coding.
JavaScript language design has quite many dusty corners, and the Boolean is one of them; it is not used in practice.
This:
var a = [];
alert(a instanceof Array);
will tell you "true". But this:
var b = true;
alert(b instanceof Boolean);
for some reason will show "false".
In short: forget about it.
Creating a new boolean object "basically" runs the bit of code in the statement and then from there returns the true boolean value.
From the same docs:
1 var b = new Boolean(false);
2 if (b) // this condition evaluates to true
https://developer.mozilla.org/en/JavaScript/Guide/Statements#if...else_Statement