Jul 18

The wrapper object trick

Posted in Javascript      Comments Off on The wrapper object trick

Whenever people ask me what I think about the JavaScript wrapper objects (ex.: String, Number, etc.), I tend to tell them that it’s better to forget that they exist and simply use the literal values (and simply let the runtime perform the conversions between literal an wrapper object automatically and whenever it’s needed). I tend to abide by this rule but today, when I was talking to an old friend, I remember an trick which I’ve learned some time ago which justified the direct use of the wrapper object: I’m talking about (what I call) the wrapper object trick. Here’s some code which illustrates its use:

var someObject = new Boolean(true);
someObject.someOtherProperty = true;
someObject.somethingElse = { id: 1, name: "hello" };

If you’re a Modernizr user, then you’ve probably recognize this kind of object! No…really? ok, then take a look at the following Modernizr tests:

if ( {
    if ( === "probably") {

And now you’ve probably understand what I’m talking about, right? What we’re doing is taking advantage of the fact that Boolean is an object and that means we can add properties to it. If you take a look at the Modernizr source code, you’ll notice that it’ll only create an object whenever it knows that the receiving literal Boolean is true. And there’s a reason for that behavior: since new Boolean ends up creating an object, then a Boolean instance will always evaluate to true in any test. Here’s an example of what I mean:

var someObject = new Boolean(false);
if (someObject) { //alwayks true

So, we need to change the code so that it behaves correctly. Here’s how you’re supposed to write the previous snippet:

var aux = (function (initValue) {
    if (initValue) {
        var someObject = new Boolean(initValue);
        someObject.someOtherProperty = true;
        someObject.somethingElse = { id: 1, name: "hello" };
        return someObject;
    return initValue;


And now, it all depends on the values you pass to the anonymous function. If you pass it false, then that’s it: you’ll end up with a literal false Boolean. If you pass it true, then you’ll get a slightly modified Boolean object. Unfortunately, I forgot to add this technique to my JavaScript book. If you’ve bought it, please add an URL to this post on section 7.2 Smile

And that’s it for now. Stay tuned for more.