Careful about using wrapper types in JavaScript

We are aware that JavaScript provides 5 Primitive Types, namely string,  boolean, number, undefined and  null. These types except null and undefined have their own wrappers that create an object version  of  these types.

I will use String type to illustrate my point above.

We create a primitive string…

    var strPrimitive = "Hello World"   // Primitive string

and its object equivalent..

    var strObj = new String("Hello World"); // Object hash of the string

So, we might assume it is fine to use any of the Primitive or its Wrapper type in our code. But, be aware of the following pitfalls,

  • Observe that, the primitive and its wrapper types aren’t the same for obvious reasons (Primitives => string literal; Wrapper => string object)

     strPrimitive == strObj // false
     strPrimitive === strObj // false.

  • Also, JavaScript auto converts primitive to object as and when necessary and vice-versa. This perhaps explains why all the methods on the String prototype are available to the primitives.
  • Using the primitive types also saves some memory on Heap, which otherwise have to be allocated for the objects.

Using wrapper types is also discouraged for the following scenarios, particularly with Boolean type.

A simple boolean primitive would look like:

   var bool = false;

This works good in our code while doing something like this:

   if(bool){ // Do something if true...}

But consider what would happen if you were to use the wrapper instead of the primitive.

   var bool = new Boolean(false);

Now, doing so would prove to be fatal!, as the below code would evaluate to be true since objects are truthy.

   if(bool){ // Do something if true...}

So, the correct way to check would be using valueOf;

   if(bool.valueOf()){ // Do something if true...}

In all, it is best to avoid using wrappers when we can accomplish the same using the simple primitives.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s