Yogesh Chauhan's Blog

Why it’s not a good idea to create Number objects in JavaScript?

in JavaScript on 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.


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to scroll contents of a an element vertically using JavaScript?JavaScriptHow to create and store JSON objects in localStorage using JavaScript?JavaScriptHow to hide and show menu on scroll using JavaScript and CSS?CSSHow to show widgets on the Appearance tab in WordPress?WordPressHow to create HTML elements with ID and class using JavaScript?HTMLMySQL queries to get data rows from previous month as well as from last 30 daysSQL/MySQL