SlavaSt SlavaSt - 4 months ago 8
Javascript Question

What are Object() and Object(value) for in JavaScript

I stumbled upon such usage in

polyfill code:

var O = Object(this);


What are the semantics of this function? Links to documentation would be welcome too.

Answer

The Object constructor, when called as a function, attempts to convert the argument to an object, as follows:

  • If the argument is already an object, it returns it.
  • If the argument is object-coercible (boolean, number, string or symbol), it coerces it to an object.
  • If the argument is null or undefined, or no argument is passed, it returns a new ordinary object that inherits from Object.prototype. Like if you used ({}).

Examples:

var obj = [1,2,3], symb = Symbol();

// Object argument
Object(obj);    // obj;

// Object-coercible argument
Object(true);   // Boolean { [[BooleanData]]: true }
Object(1234);   // Number  { [[NumberData]]: 1234 }
Object("ab");   // String  { [[StringData]]: "ab", 0: "a", 1: "b", length: 2 }
Object(symb);   // Symbol  { [[SymbolData]]: symb }

// Non-object-coercible argument
Object(null);   // Object {  }
Object(void 0); // Object {  }
Object();       // Object {  }

The polyfill uses Object(this) because the spec says Array.prototype.includes should use ToObject, but that's an internal thing which is not exposed to JS code.