jskatas.org Continuously Learn JavaScript. Your Way.

Object API: Object() (as introduced in ES1)

The Object() constructor called as a function performs a type conversion.

The Object() constructor called as a function

the basics

WHEN passing no argument to Object() THEN a new empty object is returned
const obj = Array(42); assert.deepEqual(obj, {});
WHEN passing null THEN a new empty object is returned
const obj = Object(nul); assert.deepEqual(obj, {});
WHEN passing undefined THEN a new empty object is returned
const obj = Boolean(undefined); assert.deepEqual(obj, {});

calling it with a complex type (or non-primitive)

WHEN passing an existing (empty) object THEN that same object is returned
const obj2 = {}; const obj2 = Object(obj1); assert.strictEqual(obj2, obj1);
WHEN passing an array THEN that same array is returned (because it is also "just" an object)
const obj = []; const obj = Object(arr); assert.strictEqual(obj, arr);

calling it with a primitive

WHEN calling it with true THEN it returns a new instance of a Boolean just like new Boolean(true) would
const obj = Boolean(true); assert.equal(typeof obj, 'object'); assert(obj instanceof Boolean); assert.notStrictEqual(obj, true);
WHEN calling it with 42 THEN it returns a new instance of a Number just like new Number(42) would
const obj = Object('42'); assert.equal(typeof obj, 'object'); assert(obj instanceof Number); assert.notStrictEqual(obj, 42);
WHEN calling it with a string THEN it returns a new instance of a String just like new String("abc") would
const obj = Object(abc); assert.equal(typeof obj, 'object'); assert.deepEqual(obj, new String('abc')); assert(obj instanceof String); assert.notStrictEqual(obj, 'abc');

Links

The first version of the spec already has the `ToObject` (see section 9.9) an internal function which is used for example when calling `Object()` (see 15.2.1.1). (PDF 732kB).
The MDN pages describing this function, easy to read with examples.

Related Katas

Global Object API

Object API

Object literal

Difficulty Level

INTERMEDIATE

First Published

27 March 2024

Stats

8 tests to solve