Primitives vs. Constructed Objects in JavaScript

A user asked me a question in a recent training session.

Can you use a constructor to create primitives?

In other words:

var x = new Boolean(false);

I thought about it, and answered, “Sure. But why?” I mean, we aren’t programming in Java here. This type of constructor is also dangerous.

// Don't do this in production
var maybeAlertUser = new Boolean(false);

(maybeAlertUser  === true); // this is false, but ...

if (maybeAlertUser) {
    // this always alerts
    alert("Houston, we have a problem"); 
}

alert(typeof maybeAlertUser); // object

We discussed that it is safe to use the object to type cast:

var x = 0;
var maybeAlertUser = Boolean(x);

if (maybeAlertUser) {
    // this never alerts
    alert("Houston, we have a problem"); 
}

(maybeAlertUser === false); // yup!

The JavaScript idiom to use negation operator seems to be just as safe. In this instance, the first operation converts zero to a boolean and inverts the value (turning it to true). And the second inverts the value (turning it to false), but it strikes terror into Java coders.

 
var x = 0;
var maybeAlertUser = !! x;

if (maybeAlertUser) {
    alert("Houston, we have a problem"); // never alerts
}

(maybeAlertUser === false); // yup!

Which do you prefer?

Leave a Reply

Your email address will not be published. Required fields are marked *