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

javascript

Solution

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('john@example.com');

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 = 'john@example.com'; // 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.

Problem

When are Javascript datatypes supposed to be declared as object? They slow down execution speed, and produce nasty side effects, so Why is this possible? According to W3Schools:http://www.w3schools.com/js/js_numbers.asp Also from http://www.w3schools.com/js/js_datatypes.asp

Original source

Related problems