When is it advisable to declare String, Number and Boolean as Objects in Javascript

Numbers, strings and booleans can be both primitives and objects. For example you can create a string which is a primitive, and you can create an other which is an object:

var name = 'John Doe';
var email = new String('[email protected]');

The difference is that objects (in this case email) have a lot of useful string manipulation methods. Because of that objects require more memory than primitives. So it's advised to create only primitive values and make the object conversion only when needed. JavaScript does this automatically. For example:

var name = 'John Doe'; // This is a primitive.
var email = '[email protected]'; // This is an other primitive.

The concatenation of the two is an other primitive:

var to = name + ' <' + email + '>';

However when a method is invoked on the primitive, temporarily email becomes an object:

var index = email.indexOf('@');

Because the conversion to object is happening automatically, you don't need to worry about that. Declare your variables as primitives and JavaScript will convert it to an object when needed.


Declaring String, Number and Boolean as object results in:

  1. Slow Performance: creating an object via new keyword is always costly and results in slow execution because it sets a lot of properties and performs underlying activities before returning the object instance. For more detail check below link for details on each operation performed by new keyword. https://zeekat.nl/articles/constructors-considered-mildly-confusing.html

  2. Nasty side effects: when you declare string, number and boolean as object you can face real issues when trying to compare. eg:

    var x = "Hello";
    var y = new String("Hello");
    console.log (x===y) // false because x is String n y is object 
    
    var x = new String("Hello");
    var y = new String("Hello");
    console.log(x==y); // false because objects can't be compared
    

Tags:

Javascript