The global function Boolean() can be used to cast when called without new , for example
var foo = Boolean(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, since primitives cannot save properties:
var foo = true; foo.baz = 'quux'; alert(foo.baz); // `foo.baz` is `undefined`
Assigning a property to a primitive does not lead to an error due to automatic boxing, i.e.
foo.baz = 'quux';
will be interpreted as
// create and immediately discard a wrapper object: (new Boolean(foo)).baz = 'quux';
To return a primitive value, you have to call the valueOf() method. This is necessary if you want to actually use the wrapped value, because objects always evaluate true in Boolean contexts - even if the wrapped value is false .
I have never come across a useful application that allows you to assign properties to logical values, but boxing can be useful in cases where you need a reference to a primitive value.
Christoph May 13 '09 at 9:35 a.m. 2009-05-13 09:35
source share