30

I am reading through the Mozilla Manual on JavaScript, and I come to this point in my reading, Boolean object. I can't see a single use for them. What's their point? Why wouldn't you use just true and false?

By the way, I don't know Java at all and I'm not afraid of learning new things that consequently why I'm trying to learn JavaScript. I'm a PHP programmer, a back end guy, and I'd like to learn how to do some front end work, so I'm reading the Mozilla JavaScript Guide.

hippietrail
  • 15,848
  • 18
  • 99
  • 158
Mark Tomlin
  • 8,593
  • 11
  • 57
  • 72
  • See also [What is the purpose of new Boolean() in Javascript?](http://stackoverflow.com/q/856324/1048572) – Bergi Sep 17 '15 at 16:32

9 Answers9

15

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.

10

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
c-smile
  • 26,734
  • 7
  • 59
  • 86
  • 5
    It's not just "some reason", the reason is that `true` is primitive, while `Boolean` is object. It's same as `1 instanceof Number == false` – Qwerty Jul 13 '17 at 14:18
6

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

DefconRhall
  • 293
  • 1
  • 9
  • So, it allows me to hook into the if statement without having the call that object's methods explicitly because it is done so intrinsically? What method would I think over write to get this functionality, it's constructor? – Mark Tomlin May 26 '11 at 02:26
  • Correct way to obtain the value of a boolean Object is `b.valueOf()`. `if (b)` is always true for any object, even `if ({}) ...` is true. – Qwerty Jul 13 '17 at 14:20
5
Boolean.prototype.bang = function() {
    return !this.valueOf();
}

true.bang(); // false

Everything in JavaScript is an object. But at the same time we also have primitives. It's really confusing, just don't overthink it.

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • This is really interesting! `true instanceof Boolean // false` but extending Boolean object affects it. Can you add links for more info? This is quite challenging to search for. – Qwerty Jul 13 '17 at 14:39
4

Perhaps because JavaScript objects are extensible in ways that primitives aren't? (I'm just guessing here, I've never had a need for Boolean.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408
  • 1
    No, that’s not true. Given `Boolean.prototype.someMethod = () => console.log(1);`, `true.someMethod();` is exactly the same as `Object(true).someMethod();` and `new Boolean(true).someMethod()` and `Boolean.prototype.someMethod.call(true)`, etc., and works just fine. Property access always coerces the left-hand value to an object. – Sebastian Simon Jan 07 '22 at 17:58
3

From the documentation:

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. Any object whose value is not undefined , null, 0, NaN, or the empty string , including a Boolean object whose value is false, evaluates to true when passed to a conditional statement.

Imagine the following scenario:

if(SomeBoolean){...}

will be true in scenarios where SomeBoolean is a Boolean object.

Conversely:

if(false){...}

will always be false

Addendum for clarification.

var someString = new Boolean("MyNonEmptyString")
if(someString) //true
var otherString = new Boolean("")
if(otherString) //false
Lawrence Dol
  • 63,018
  • 25
  • 139
  • 189
Woot4Moo
  • 23,987
  • 16
  • 94
  • 151
  • 6
    That seems to argue why you *shouldn't* use the Boolean object, not why you should. – Paul Tomblin May 26 '11 at 02:05
  • I don't like the example. `SomeBoolean` will always be true where it is a Boolean object, or where it has been assigned a "truthy" value. The "converse" case isn't really converse, it should be `if (false)` will always be false. – RobG May 26 '11 at 02:17
  • @RobG for you I changed it to false and contrapositive. – Woot4Moo May 26 '11 at 02:21
  • 1
    This seems to be in contrast with other answers. The last condition, `if(otherString)`, is `true` for me: http://jsbin.com/ijixi3 – Kobi May 26 '11 at 05:20
  • @Kobi my declaration of `""` should translate into the empty string. – Woot4Moo May 26 '11 at 13:53
  • 1
    @Woot4Moo - I'm not sure I understand... Did you try running your code? I get `true` on `if(otherString) //false`. – Kobi May 26 '11 at 15:11
  • @Kobi no I did not run the code, because in every language I have ever used `""` is equal to `empty string`. Furthermore the link you provided me I refuse to go to because that opens me up quite nicely to XSS. – Woot4Moo May 26 '11 at 15:58
  • 1
    @Woot4Moo - Of course `""` is an empty string. I asked if you run the code that you wrote. Any way, never mind, but you are wrong (and have a fuzzy idea of what XSS is, but that's another matter `:)`). – Kobi May 26 '11 at 17:05
  • @Kobi I am not even getting into the argument with you over what XSS is and is not. Go complain to the implementors of JavaScript if their documentation is incorrect. – Woot4Moo May 26 '11 at 17:11
  • `otherString` evaluates to `true` as you are actually coercing an object to a boolean, which is always true for any object. Though the real value of it is indeed false`otherString.valueOf() == false` – Qwerty Jul 13 '17 at 14:28
2

You can coerce a true or false from any value with return Boolean(something), but it's shorter to write return !!something, which forces a true or false as well.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kennebec
  • 102,654
  • 32
  • 106
  • 127
  • 1
    Good detail with the forcing of a `true` of `false` return value with `!!`. +1, but it does not answer my question. – Mark Tomlin May 26 '11 at 23:48
1

I would have to side with most of the people here that there isn't much need for the Boolean object, but I do want to point out a couple of things.

An explicit comparison will still evaluate like a boolean:

var someBool = new Boolean(false);
if (someBool == false)
    alert('Got here'); //Alerts 'Got here'

Because of this, you could sort of extend it to a subclass and still be able to have the comparison work as above:

var classExtension = {
    toYN: function() {
        return this == false ? 'N' : 'Y';
    }
};

function getNewClass(val) {
    var newBool = new Boolean(val);
    jQuery.extend(newBool, classExtension);
    return newBool;
}

var newTest = getNewClass(false);
if (newTest)
    alert('It\'s alive');
if (newTest == false)
    alert('And still a bool');
alert(newTest.toYN());

This will alert 'It's alive', 'And still a bool' and 'N'. http://jsfiddle.net/fkJuk/

But again, would you ever really need this? Even if you did, it would probably be better just to have your own separate class with a boolean property that gets checked. In the end, it's probably here for consistency; every primitive has direct constructor and prototype access in JavaScript.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matt Molnar
  • 2,412
  • 3
  • 22
  • 28
0

Going back to the specification (ECMA-262.pdf page 151), note that when Boolean is called as a function rather than as a constructor, it does type conversion. Thus:

var t = 5
  , f = 0

console.log(Boolean(t))  //Prints true
console.log(Boolean(f))  //Prints false

Of course, being a JavaScript object, you can use it as a prototype using the 'new' operator, as others have noted, but I don't see any reason for doing that.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tamzin Blake
  • 2,594
  • 20
  • 36