views:

472

answers:

3

what is the use of

var flag = new Boolean(false);

in compare to

var flag = false;

when would you actually use new Boolean?

+5  A: 

Boolean primitives and boolean objects are not the same. MDC Docs:

Any object whose value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement.

This behavior does not apply to Boolean primitives.

The purpose of the boolean object is to convert non boolean objects into a boolean.

apphacker
A: 

You can use the prototype to define functions that do custom operations on the Boolean, I think that would be the use of it compared to just using a primitive.

Also I think there is an effort going on making javascript similar to other languages since javascript is often used for communication from webservices (using JSON).

PQW
+7  A: 

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.

Christoph