var a = 10
var b = new Number(10)
console.log(a instanceof Number)
console.log(b instanceof Number)
can anyone please let me know what is the difference between above two declaration and definition of a and b.
var a = 10
var b = new Number(10)
console.log(a instanceof Number)
console.log(b instanceof Number)
can anyone please let me know what is the difference between above two declaration and definition of a and b.
Explicitly stating that you are creating a new number with new Number(10)
creates a new wrapper object for the number, whereas simply defining a number as a variable creates a integer primitive value. As such, you get differing results when checking their typeof
:
var a = 10;
var b = new Number(10);
console.log(typeof a);
console.log(typeof b);
Hope this helps! :)
The first creates a primitive. The other an object.
The primary uses for the Number object are:
1) If the argument cannot be converted into a number, it returns NaN.
2) In a non-constructor context (i.e., without the new operator), Number can be used to perform a type conversion.
In theory there is a difference but in practice none. The JavaScript engine automagicly boxes a primitive to an object when it needs to be an object.
var number = 42;
// calling .toFixed will 'box' the primitive into a number object,
// run the method and then 'unbox' it back to a primitive
console.log( number.toFixed(2) );
The only usage I've found is if you want to return a primitive from a constructor function.
function Foo() {
return 42;
}
var foo = new Foo();
console.log(foo); // foo is instance of Foo
function Bar() {
return new Number(42);
}
var bar = new Bar();
console.log(bar); // bar is instance of Number
remind that
new Number(10) == new Number(10) return false
The first declaration is like primitive datatype.
While in your second declaration where you used new Number(10)
, it is considered like a wrapper function or class
to preserve your number in an object
.
To see the actual difference, check now the actual type of your variables in both cases:
console.log(typeof(a)) //should give you "number"
console.log(typeof(b)) //should give you "object"
The var
keyword is just a simple declaration of a variable. The new
keyword is used to generate a new object
of some type. You'll need to look into objects in programming in general in order to fully understand them.