Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript declaring number in different ways?

Tags:

javascript

var a = 1;
var b = Number(1);
var c = new Number(1);

I was wondering what is the difference between these three statements. I understand that first and second statements are same, as if(a===b) gives true, but the third one will create a object of type number.

What I want to know is how these methods are different, and any advantages one will give over the other?

like image 670
GajendraSinghParihar Avatar asked Sep 10 '12 15:09

GajendraSinghParihar


1 Answers

A value like 1 is a primitive, not an object. JavaScript will generally promote numbers to Number objects when necessary. There's rarely a reason to explicitly construct one, and there's certainly no particular "advantage". There's also no reason for something like Number(1), though the Number constructor is one of several ways of coercing a value to be a number.

like image 183
Pointy Avatar answered Sep 28 '22 07:09

Pointy