What is the difference between a number stored in a normal variable:
var foo = 5;
And a number object:
var bar = new Number(5);
What can I use a number object for?
What is the difference between a number stored in a normal variable:
var foo = 5;
And a number object:
var bar = new Number(5);
What can I use a number object for?
A Number
object contains some useful methods and properties such as:
Method Description
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
toExponential(x) Converts a number into an exponential notation
toFixed(x) Formats a number with x numbers of digits after the decimal point
toPrecision(x) Formats a number to x length
toString() Converts a Number object to a string
valueOf() Returns the primitive value of a Number object
Property Description
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
constructor Returns the function that created the Number object's prototype
MAX_VALUE Returns the largest number possible in JavaScript
MIN_VALUE Returns the smallest number possible in JavaScript
NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
NaN Represents a "Not-a-Number" value
POSITIVE_INFINITY Represents infinity (returned on overflow)
prototype Allows you to add properties and methods to an object
I think in practice there is no difference between this two. All available methods for number objects is also available for primitive numbers. When you invoke a method on a primitive number, the number temporarily gets converted to an object and then the method executes. See the following examples:
var temp1 = Object(1) // number object
var temp2 = 1 // primitive number
console.log(temp1.toString()) // invoke its own method. result: 1
console.log(temp2.toString()) // temporarily converts to object and invoke number object method. result:1
console.log(Object(1).constructor === Number) //true
console.log((1).constructor === Number) //true
// ^---------- temporarily converts to object
var foo = 5;
typeof(foo); // Is Number
var bar = new Number(5);
typeof(bar); // Is object
When you go down to advanced level in JavaScript, you have certain properties for objects which you can't invoke on numbers, so it is up to you to draw a line and see what to use where.
Numbers – e.g. 5, 3e+10 (all numbers behave as floats – significant for division, but can be truncated by x >>> 0). Sometimes boxed. Instance of Number when boxed.
Objects – e.g. {foo: 'bar', bif: [1, 2]}, which are really just hashtables. Always boxed. Instance of Object.