Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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 enter image description here Also from http://www.w3schools.com/js/js_datatypes.asp enter image description here

like image 800
Dave Avatar asked Jul 07 '14 22:07

Dave


2 Answers

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.

like image 58
Gergo Erdosi Avatar answered Sep 18 '22 08:09

Gergo Erdosi


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
    
like image 32
shilpa Avatar answered Sep 20 '22 08:09

shilpa