Cairo Stewart Cairo Stewart - 2 months ago 8
Javascript Question

What happens when you instantiate a new Object(1) with a parameter in JavaScript?

What happens when you call:

new Object(1)


When I tried it out, it returned:

[Number: 1]


I want to understand what is going on there. Any info would be appreciated.

Answer

You can look at the spec:

When new Object(arg) is invoked, we are essentially calling ToObject(arg).

ToObject is defined as

The abstract operation ToObject converts argument to a value of type Object according to Table 13

And the table says:

Number: Return a new Number object whose [[NumberData]] internal slot is set to the value of argument. See 20.1 for a description of Number objects.

So it's the same as calling new Number(1), i.e. it creates a number object.


The primitive data types String, Number and Boolean have equivalent object values that can be created by invoking the equivalent constructor functions. But that is not a common thing to do since object values behave differently than primitive values, i.e. a number primitive will behave different than a number object in certain cases.

Example:

Boolean(0); // false
Boolean(new Number(0)); // true