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
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:
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With