YogeshChauhan.com
Why it’s not a good idea to create Number objects in JavaScript?
May 5, 2020

Numbers Can be Objects

JavaScript numbers are primitive values created from literals:


var x = 1;

But numbers can also be defined as objects with the keyword new:


var y = new Number(1);

If we check it's type:


var x = 1;
var y = new Number(1);
console.log(typeof(x));
console.log(typeof(y));

//number
//object

The first reason why we should not create number objects is that it slows down execution speed.

The keyword new complicates the code which can produce some unexpected results:

When we use  == operator, equal numbers are equal.

For example, if we compare the above number and object it should result in true based on the value.


var x = 1;
var y = new Number(1);
console.log(x==y); //true

But when we use the === operator, equal numbers are not equal because the === operator expects equality in both type and value.

For example, if we compare the above number and object using === operator, it should result in false based on the value and type.


var x = 1;
var y = new Number(1);
console.log(x===y); //false

So, the second reason is comparison can give different results.

The third reason is because objects cannot be compared, the numbers objects won't make any sense while comparing.

So, if create 2 objects of numbers and then try to compare them, it will result in false.

For example:


var x = new Number(1);
var y = new Number(2);
console.log(x==y); //false

Comparing two JavaScript objects will always return false.

dreamhost

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 5 How to create flickering text using CSS? Mar 4 How to use data-* Attributes in HTML? Mar 4 The substr() method in JavaScript and how it’s different from substring() Mar 4 A complete guide to add responsive YouTube videos using HTML and CSS Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress?

You might also like these

Why it’s not a good idea to create Number objects in JavaScript?JavaScript5 Steps to Create a Line using Canvas Tag in HTML5HTMLCROSS JOIN in PostgresPostgresHow to hide a DIV on clicks outside of it using jQuery?jQueryPostgreSQL transactions using the BEGIN, COMMIT, and ROLLBACK statements.PostgresLearn to make a responsive gallery using CSS Grid and without media queriesCSS