Cairo Stewart
Cairo Stewart

Reputation: 43

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.

Upvotes: 4

Views: 86

Answers (2)

Dániel Kis
Dániel Kis

Reputation: 2631

Here is the documentation for the default constuctor: http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.2.1

When the Object constructor is called with no arguments or with one argument value, the following steps are taken:

  • If value is supplied, then
    • If Type(value) is Object, then
      • If the value is a native ECMAScript object, do not create a new object but simply return value.
      • If the value is a host object, then actions are taken and a result is returned in an implementation-dependent manner that may depend on the host object.
    • If Type(value) is String, return ToObject(value).
    • If Type(value) is Boolean, return ToObject(value).
    • If Type(value) is Number, return ToObject(value).
  • Assert: The argument value was not supplied or its type was Null or Undefined.
  • Let obj be a newly created native ECMAScript object.
  • Set the [[Prototype]] internal property of obj to the standard built-in Object prototype object (15.2.4).
  • Set the [[Class]] internal property of obj to "Object". Set the [[Extensible]] internal property of obj to true.
  • Set all the internal methods of obj as specified in 8.12.
  • Return obj.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816424

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

Upvotes: 6

Related Questions