What is the purpose of new Boolean() in Javascript?

Viewed 23849

What is the use of:

var flag = new Boolean(false); 

compared to:

var flag = false;

When would you actually use new Boolean?

4 Answers

The global function Boolean() can be used for type casting when called without new, eg

var foo = Boolean(bar); // equivalent to `var foo = !!bar`

When called with new, a wrapper object will be created additionally, which means that you can assign arbitrary properties to the object:

var foo = new Boolean(bar); // equivalent to `var foo = Object(Boolean(bar));`
foo.baz = 'quux';
alert(foo.baz);

This is not possible with primitive values as primitives can't hold properties:

var foo = true;
foo.baz = 'quux';
alert(foo.baz); // `foo.baz` is `undefined`

Assigning a property to a primitive doesn't produce an error because of auto-boxing, ie

foo.baz = 'quux';

will be interpreted as

// create and immediately discard a wrapper object:
(new Boolean(foo)).baz = 'quux';

To get the primitive value back, you'll have to invoke the valueOf() method. This is needed if you want to actually use the wrapped value, because objects always evaluate to true in boolean contexts - even if the wrapped value is false.

I've never come across a useful application of being able to assign properties to booleans, but boxing might be useful in cases where a reference to a primitive value is needed.

Related