In Javascript, one of the reliable ways to convert a string to a number is the Number
constructor:
var x = Number('09'); // 9, because it defaults to decimal
Inspired by this question, I started wondering — what is the difference between the above and:
var x =new Number('09');
Number
certainly looks better, but it seems like a slightly inappropriate use of a constructor. Are there any side effects or any difference to using it without the new? If there is no difference, why not, and what is the purpose of new?
Creates a new Number value. When Number is called as a constructor (with new ), it creates a Number object, which is not a primitive. For example, typeof new Number(42) === "object" , and new Number(42) !== 42 (although new Number(42) == 42 ).
Javascript Number() Function object: This parameter holds the objects that will be converted any type of javascript variable to number type. Return Values: Number() function returns the number format for any type of javascript variable. Example 2: Not a number is returned by the compiler.
++ increases the integer by one and += increases the integer by the number of your choice.
In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.
In the first case, you are using the Number Constructor Called as a Function, as described in the Specification, that will simply perform a type conversion, returning you a Number
primitive.
In the second case, you are using the Number
Constructor to make a Number
object:
var x = Number('09');
typeof x; // 'number'
var x = new Number('09');
typeof x; // 'object'
Number('1') === new Number('1'); // false
The difference may be subtle, but I think it's important to notice how wrapper objects act on primitive values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With