0

What is the difference between var a and var a = new Number() and later assigning the value of a to 1

When consoled I see one as undefined and one has Number{}. What would be the most notable differences to be known as implementation progresses.

Raviteja Avvari
  • 252
  • 4
  • 14
  • 1
    A case of primitive vs object. Don't use `new Number`. – elclanrs Mar 30 '15 at 08:58
  • 1
    If you later assign it a new value then it makes absolutely no difference what you use to initialize it. – JJJ Mar 30 '15 at 08:59
  • 1
    Not a dupe but might answer your question: http://stackoverflow.com/questions/369220/why-should-you-not-use-number-as-a-constructor – Salman A Mar 30 '15 at 09:00
  • 2
    The first creates a primitive. The other an object. For correct answer: http://stackoverflow.com/questions/27083391/what-is-the-difference-between-var-num-30-and-var-num-new-number30-in-javascri – choudhury smrutiranjan parida Mar 30 '15 at 09:01

2 Answers2

0

The difference is that you shouldn't use new Number().
new Number creates an object, which will be overridden the moment you assign some other value to it. The other just creates a primitive.

The only reason you'd use Number is to parse strings to numeric values:

var a = Number("1e20"),
    b = Number("1.6");

(Keep in mind there's parseInt and parseFloat as well.)

Or to access a couple of constants:

var biggestNum = Number.MAX_VALUE;
var smallestNum = Number.MIN_VALUE;
var infiniteNum = Number.POSITIVE_INFINITY;
var negInfiniteNum = Number.NEGATIVE_INFINITY;
var notANum = Number.NaN;

Don't use Number as a declaration like that. There's really no point in doing so.

If you're only as assigning numeric values to variables, without any kind of parsing, just assign them:

var a = 5,
    b = 5234;
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
-2

Number() allows you to parse strings or other variable types, it is not meant as declaration, since variables don't have types in javascript.

http://www.w3schools.com/jsref/jsref_number.asp

Maarten
  • 7
  • 1
  • 1
    Referencing w3schools is generally frowned upon on Stack Overflow. Try to use [mdn](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) instead. – Cerbrus Mar 30 '15 at 09:07