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.