Object constructor
The Object() constructor turns the input into an object. Its behavior depends on the input’s type.
Syntax
new Object() new Object(value) Object() Object(value)
Note: Object() can be called with or without new, but sometimes with different effects. See Return value.
Parameters
value Optional - Any value.Return value
When the Object() constructor itself is called or constructed, its return value is an object:
value is null or undefined, it creates and returns an empty object.value is an object already, it returns the value.bigInt primitive returns a BigInt wrapper object.Object() is constructed but new.target is not the Object constructor itself, the behavior is slightly different — it initializes a new object with new.target.prototype as its prototype. Any argument value is ignored. This may happen, for example, when Object() is implicitly called via super() in the constructor of a class that extends Object. In this case, even if you pass a number to super(), the this value inside the constructor does not become a Number instance.“Object() constructor - JavaScript | MDN” (MDN Web Docs). Retrieved January 8, 2024.
Object.assign()
The Object.assign() static method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
Syntax
Object.assign(target) Object.assign(target, source1) Object.assign(target, source1, source2) Object.assign(target, source1, source2, /* …, */ sourceN)
Parameters
target - The target object — what to apply the sources’ properties to, which is returned after it is modified.source1, …, sourceN - The source object(s) — objects containing the properties you want to apply.Return value
The target object.
“Object.assign() - JavaScript | MDN” (MDN Web Docs). Retrieved January 8, 2024.
Object.create()
The Object.create() static method creates a new object, using an existing object as the prototype of the newly created object.
Syntax
Object.create(proto) Object.create(proto, propertiesObject)
Parameters
proto - The object which should be the prototype of the newly-created object.propertiesObject Optional - If specified and not undefined, an object whose enumerable own properties specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of Object.defineProperties().Return value
Exceptions
TypeError - Thrown if proto is neither null nor an Object.Example
o = {};
// Is equivalent to:
o = Object.create(Object.prototype);
o = Object.create(Object.prototype, {
// foo is a regular data property
foo: {
writable: true,
configurable: true,
value: "hello",
},
// bar is an accessor property
bar: {
configurable: false,
get() {
return 10;
},
set(value) {
console.log("Setting `o.bar` to", value);
},
},
});
// Create a new object whose prototype is a new, empty
// object and add a single property 'p', with value 42.
o = Object.create({}, { p: { value: 42 } });“Object.create() - JavaScript | MDN” (MDN Web Docs). Retrieved January 8, 2024.
Object.defineProperties()
The Object.defineProperties() static method defines new or modifies existing properties directly on an object, returning the object.
Syntax
Object.defineProperties(obj, props)
Parameters
obj - The object on which to define or modify properties.props - An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. Each value in props must be either a data descriptor or an accessor descriptor; it cannot be both (see Object.defineProperty() for more details).Data descriptors and accessor descriptors may optionally contain the following keys:
configurable - true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. Defaults to false.enumerable - true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to false.A data descriptor also has the following optional keys:
value - The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). Defaults to undefined.writable - true if and only if the value associated with the property may be changed with an assignment operator. Defaults to false.An accessor descriptor also has the following optional keys:
get - A function which serves as a getter for the property, or undefined if there is no getter. The function’s return value will be used as the value of the property. Defaults to undefined.set - A function which serves as a setter for the property, or undefined if there is no setter. The function will receive as its only argument the new value being assigned to the property. Defaults to undefined.If a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. If a descriptor has both value or writable and get or set keys, an exception is thrown.
Return value
Examples
const obj = {};
Object.defineProperties(obj, {
property1: {
value: true,
writable: true,
},
property2: {
value: "Hello",
writable: false,
},
// etc. etc.
});“Object.defineProperties() - JavaScript | MDN” (MDN Web Docs). Retrieved January 9, 2024.
Object.defineProperty()
The Object.defineProperty() static method defines a new property directly on an object, or modifies an existing property on an object, and returns the object.
Syntax
Object.defineProperty(obj, prop, descriptor)
Parameters
obj - The object on which to define the property.prop - A string or Symbol specifying the key of the property to be defined or modified.descriptor - The descriptor for the property being defined or modified. It must be either a data descriptor or an accessor descriptor; it cannot be both.Data descriptors and accessor descriptors may optionally contain the following keys:
configurable - true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. Defaults to false.enumerable - true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to false.A data descriptor also has the following optional keys:
value - The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). Defaults to undefined.writable - true if and only if the value associated with the property may be changed with an assignment operator. Defaults to false.An accessor descriptor also has the following optional keys:
get - A function which serves as a getter for the property, or undefined if there is no getter. The function’s return value will be used as the value of the property. Defaults to undefined.set - A function which serves as a setter for the property, or undefined if there is no setter. The function will receive as its only argument the new value being assigned to the property. Defaults to undefined.If a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. If a descriptor has both value or writable and get or set keys, an exception is thrown.
Return value
The object that was passed to the function, with the specified property added or modified.
“Object.defineProperty() - JavaScript | MDN” (MDN Web Docs). Retrieved January 9, 2024.
Object.entries()
The Object.entries() static method returns an array of a given object’s own enumerable string-keyed property key-value pairs.
Syntax
Object.entries(obj)
Parameters
obj - An object.Return value
An array of the given object’s own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value.
Examples
const obj = { foo: "bar", baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
const arrayLike = { 0: "a", 1: "b", 2: "c" };
console.log(Object.entries(arrayLike)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]
const randomKeyOrder = { 100: "a", 2: "b", 7: "c" };
console.log(Object.entries(randomKeyOrder)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]
// getFoo is a non-enumerable property
const myObj = Object.create(
{},
{
getFoo: {
value() {
return this.foo;
},
},
},
);
myObj.foo = "bar";
console.log(Object.entries(myObj)); // [ ['foo', 'bar'] ]“Object.entries() - JavaScript | MDN” (MDN Web Docs). Retrieved January 9, 2024.
Object.freeze()
The Object.freeze() static method freezes an object. Freezing an object prevents extensions and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object’s prototype cannot be re-assigned. freeze() returns the same object that was passed in.
Freezing an object is the highest integrity level that JavaScript provides.
Syntax
Object.freeze(obj)
Parameters
obj - The object to freeze.Return value
The object that was passed to the function.
Examples
const obj = {
prop: 42,
};
Object.freeze(obj);
obj.prop = 33;
// Throws an error in strict mode
console.log(obj.prop);
// Expected output: 42“Object.freeze() - JavaScript | MDN” (MDN Web Docs). Retrieved January 9, 2024.
Object.fromEntries()
The Object.fromEntries() static method transforms a list of key-value pairs into an object.
Syntax
Object.fromEntries(iterable)
Parameters
iterable - An iterable, such as an Array or Map, containing a list of objects. Each object should have two properties:
0 - A string or symbol representing the property key.1 - The property value.Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value.
Return value
Examples:
const entries = new Map([
['foo', 'bar'],
['baz', 42],
]);
const obj = Object.fromEntries(entries);
console.log(obj);
// Expected output: Object { foo: "bar", baz: 42 }“Object.fromEntries() - JavaScript | MDN” (MDN Web Docs). Retrieved January 10, 2024.
Object.getOwnPropertyDescriptor()
The Object.getOwnPropertyDescriptor() static method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object’s prototype chain). The object returned is mutable but mutating it has no effect on the original property’s configuration.
Syntax
Object.getOwnPropertyDescriptor(obj, prop)
Parameters
obj - The object in which to look for the property.prop - The name or Symbol of the property whose description is to be retrieved.Return value
undefined otherwise.Example
const object1 = {
property1: 42,
};
const descriptor1 = Object.getOwnPropertyDescriptor(object1, 'property1');
console.log(descriptor1.configurable);
// Expected output: true
console.log(descriptor1.value);
// Expected output: 42“Object.getOwnPropertyDescriptor() - JavaScript | MDN” (MDN Web Docs). Retrieved January 10, 2024.
Object.getOwnPropertyDescriptors()
The Object.getOwnPropertyDescriptors() static method returns all own property descriptors of a given object.
Syntax
Object.getOwnPropertyDescriptors(obj)
Parameters
obj - The object for which to get all own property descriptors.Return value
Example
const object1 = {
property1: 42,
};
const descriptors1 = Object.getOwnPropertyDescriptors(object1);
console.log(descriptors1.property1.writable);
// Expected output: true
console.log(descriptors1.property1.value);
// Expected output: 42“Object.getOwnPropertyDescriptors() - JavaScript | MDN” (MDN Web Docs). Retrieved January 10, 2024.
Object.getOwnPropertyNames()
The Object.getOwnPropertyNames() static method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.
Syntax
Object.getOwnPropertyNames(obj)
Parameters
obj - The object whose enumerable and non-enumerable properties are to be returned.Return value
Example
const object1 = {
a: 1,
b: 2,
c: 3,
};
console.log(Object.getOwnPropertyNames(object1));
// Expected output: Array ["a", "b", "c"]“Object.getOwnPropertyNames() - JavaScript | MDN” (MDN Web Docs). Retrieved January 10, 2024.
Object.getOwnPropertySymbols()
The Object.getOwnPropertySymbols() static method returns an array of all symbol properties found directly upon a given object.
Syntax
Object.getOwnPropertySymbols(obj)
Parameters
obj - The object whose symbol properties are to be returned.Return value
An array of all symbol properties found directly upon the given object.
Example
const obj = {};
const a = Symbol("a");
const b = Symbol.for("b");
obj[a] = "localSymbol";
obj[b] = "globalSymbol";
const objectSymbols = Object.getOwnPropertySymbols(obj);
console.log(objectSymbols.length); // 2
console.log(objectSymbols); // [Symbol(a), Symbol(b)]
console.log(objectSymbols[0]); // Symbol(a)“Object.getOwnPropertySymbols() - JavaScript | MDN” (MDN Web Docs). Retrieved January 10, 2024.
Object.getPrototypeOf()
The Object.getPrototypeOf() static method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object.
Syntax
Object.getPrototypeOf(obj)
Parameters
obj - The object whose prototype is to be returned.Return value
null.Non-object coercion
In ES5, it will throw a TypeError exception if the obj parameter isn’t an object. In ES2015, the parameter will be coerced to an Object.
Object.getPrototypeOf("foo");
// TypeError: "foo" is not an object (ES5 code)
Object.getPrototypeOf("foo");
// String.prototype (ES2015 code)Example
const prototype1 = {};
const object1 = Object.create(prototype1);
console.log(Object.getPrototypeOf(object1) === prototype1);
// Expected output: true“Object.getPrototypeOf() - JavaScript | MDN” (MDN Web Docs). Retrieved January 10, 2024.
Object.groupBy()
The Object.groupBy() static method groups the elements of a given iterable according to the string values returned by a provided callback function. The returned object has separate properties for each group, containing arrays with the elements in the group.
This method should be used when group names can be represented by strings. If you need to group elements using a key that is some arbitrary value, use Map.groupBy() instead.
Syntax
Object.groupBy(items, callbackFn)
Parameters
items - An iterable (such as an Array) whose elements will be grouped.callbackFn - A function to execute for each element in the iterable. It should return a value that can get coerced into a property key (string or symbol) indicating the group of the current element. The function is called with the following arguments:
element - The current element being processed.index - The index of the current element being processed.Return value
A null-prototype object with properties for all groups, each assigned to an array containing the elements of the associated group.
Example
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
{ name: "fish", type: "meat", quantity: 22 },
];
const result = Object.groupBy(inventory, ({ type }) => type);
/* Result is:
{
vegetables: [
{ name: 'asparagus', type: 'vegetables', quantity: 5 },
],
fruit: [
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "cherries", type: "fruit", quantity: 5 }
],
meat: [
{ name: "goat", type: "meat", quantity: 23 },
{ name: "fish", type: "meat", quantity: 22 }
]
}
*/
function myCallback({ quantity }) {
return quantity > 5 ? "ok" : "restock";
}
const result2 = Object.groupBy(inventory, myCallback);
/* Result is:
{
restock: [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "cherries", type: "fruit", quantity: 5 }
],
ok: [
{ name: "goat", type: "meat", quantity: 23 },
{ name: "fish", type: "meat", quantity: 22 }
]
}
*/
“Object.groupBy() - JavaScript | MDN” (MDN Web Docs). Retrieved January 10, 2024.
Object.hasOwn()
The Object.hasOwn() static method returns true if the specified object has the indicated property as its own property. If the property is inherited, or does not exist, the method returns false.
Syntax
Object.hasOwn(obj, prop)
Parameters
obj - The JavaScript object instance to test.prop - The String name or Symbol of the property to test.Return valuetrue if the specified object has directly defined the specified property. Otherwise false
Example
const example = {};
example.prop = "exists";
// `hasOwn` will only return true for direct properties:
Object.hasOwn(example, "prop"); // true
Object.hasOwn(example, "toString"); // false
Object.hasOwn(example, "hasOwnProperty"); // false
// The `in` operator will return true for direct or inherited properties:
"prop" in example; // true
"toString" in example; // true
"hasOwnProperty" in example; // true“Object.hasOwn() - JavaScript | MDN” (MDN Web Docs). Retrieved January 16, 2024.
Object.prototype.hasOwnProperty()
The hasOwnProperty() method of Object instances returns a boolean indicating whether this object has the specified property as its own property (as opposed to inheriting it).
Note: Object.hasOwn() is recommended over hasOwnProperty(), in browsers where it is supported.
Syntax
hasOwnProperty(prop)
Parameters
prop - The String name or Symbol of the property to test.Return value
Returns true if the object has the specified property as own property; false otherwise.
Example
const object1 = {};
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1'));
// Expected output: true
console.log(object1.hasOwnProperty('toString'));
// Expected output: false
console.log(object1.hasOwnProperty('hasOwnProperty'));
// Expected output: false“Object.prototype.hasOwnProperty() - JavaScript | MDN” (MDN Web Docs). Retrieved January 16, 2024.
What issues does Object.prototype.hasOwnProperty() have?
Using hasOwnProperty as a property name
JavaScript does not protect the property name hasOwnProperty; an object that has a property with this name may return incorrect results:
const foo = {
hasOwnProperty() {
return false;
},
bar: "Here be dragons",
};
foo.hasOwnProperty("bar"); // re-implementation always returns falseThe recommended way to overcome this problem is to instead use Object.hasOwn() (in browsers that support it). Other alternatives include using an external hasOwnProperty:
Object.prototype.hasOwnProperty.call(foo, "bar"); // true
Objects created with Object.create(null)
null-prototype objects do not inherit from Object.prototype, making hasOwnProperty() inaccessible.
const foo = Object.create(null);
foo.prop = "exists";
foo.hasOwnProperty("prop"); // Uncaught TypeError: foo.hasOwnProperty is not a functionThe solutions in this case are the same as for the previous section: use Object.hasOwn() by preference, otherwise use an external object’s hasOwnProperty().
“Using hasOwnProperty as a property name” (MDN Web Docs). Retrieved January 16, 2024.
Object.is()
The Object.is() static method determines whether two values are the same value.
Syntax
Object.is(value1, value2)
Parameters
value1 - The first value to compare.value2 - The second value to compare.Return value
A boolean indicating whether or not the two arguments are the same value.
Important
Object.is() is not equivalent to the == operator. The == operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as "" == false being true), but Object.is() doesn’t coerce either value.
Object.is() is also not equivalent to the === operator. The only difference between Object.is() and === is in their treatment of signed zeros and NaN values. The === operator (and the == operator) treats the number values -0 and +0 as equal, but treats NaN as not equal to each other.
Examples
// Case 1: Evaluation result is the same as using ===
Object.is(25, 25); // true
Object.is("foo", "foo"); // true
Object.is("foo", "bar"); // false
Object.is(null, null); // true
Object.is(undefined, undefined); // true
Object.is(window, window); // true
Object.is([], []); // false
const foo = { a: 1 };
const bar = { a: 1 };
const sameFoo = foo;
Object.is(foo, foo); // true
Object.is(foo, bar); // false
Object.is(foo, sameFoo); // true
// Case 2: Signed zero
Object.is(0, -0); // false
Object.is(+0, -0); // false
Object.is(-0, -0); // true
// Case 3: NaN
Object.is(NaN, 0 / 0); // true
Object.is(NaN, Number.NaN); // true“Object.is() - JavaScript | MDN” (MDN Web Docs). Retrieved January 16, 2024.
Object.isExtensible()
The Object.isExtensible() static method determines if an object is extensible (whether it can have new properties added to it).
Syntax
Object.isExtensible(obj)
Parameters
obj - The object which should be checked.Return value
A Boolean indicating whether or not the given object is extensible.
Description
Objects are extensible by default: they can have new properties added to them, and their [[Prototype]] can be re-assigned. An object can be marked as non-extensible using one of Object.preventExtensions(), Object.seal(), Object.freeze(), or Reflect.preventExtensions().
Examples
// New objects are extensible.
const empty = {};
Object.isExtensible(empty); // true
// They can be made un-extensible
Object.preventExtensions(empty);
Object.isExtensible(empty); // false
// Sealed objects are by definition non-extensible.
const sealed = Object.seal({});
Object.isExtensible(sealed); // false
// Frozen objects are also by definition non-extensible.
const frozen = Object.freeze({});
Object.isExtensible(frozen); // false“Object.isExtensible() - JavaScript | MDN” (MDN Web Docs). Retrieved January 16, 2024.
Object.isFrozen()
The Object.isFrozen() static method determines if an object is frozen.
Syntax
Object.isFrozen(obj)
Parameters
obj - The object which should be checked.Return value
A Boolean indicating whether or not the given object is frozen.
Examples
// A new object is extensible, so it is not frozen.
Object.isFrozen({}); // false
// The easiest way for an object to be frozen
// is if Object.freeze has been called on it.
const frozen = { 1: 81 };
Object.isFrozen(frozen); // false
Object.freeze(frozen);
Object.isFrozen(frozen); // true
// By definition, a frozen object is non-extensible.
Object.isExtensible(frozen); // false
// Also by definition, a frozen object is sealed.
Object.isSealed(frozen); // true“Object.isFrozen() - JavaScript | MDN” (MDN Web Docs). Retrieved January 17, 2024.
Object.prototype.isPrototypeOf()
The isPrototypeOf() method of Object instances checks if this object exists in another object’s prototype chain.
Note: isPrototypeOf() differs from the instanceof operator. In the expression object instanceof AFunction, object’s prototype chain is checked against AFunction.prototype, not against AFunction itself.
Syntax
isPrototypeOf(object)
Parameters
object - The object whose prototype chain will be searched.Return value
A boolean indicating whether the calling object (this) lies in the prototype chain of object. Directly returns false when object is not an object (i.e. a primitive).
Exceptions
TypeError - Thrown if this is null or undefined (because it can’t be converted to an object).Examples
class Foo {}
class Bar extends Foo {}
class Baz extends Bar {}
const foo = new Foo();
const bar = new Bar();
const baz = new Baz();
// prototype chains:
// foo: Foo --> Object
// bar: Bar --> Foo --> Object
// baz: Baz --> Bar --> Foo --> Object
console.log(Baz.prototype.isPrototypeOf(baz)); // true
console.log(Baz.prototype.isPrototypeOf(bar)); // false
console.log(Baz.prototype.isPrototypeOf(foo)); // false
console.log(Bar.prototype.isPrototypeOf(baz)); // true
console.log(Bar.prototype.isPrototypeOf(foo)); // false
console.log(Foo.prototype.isPrototypeOf(baz)); // true
console.log(Foo.prototype.isPrototypeOf(bar)); // true
console.log(Object.prototype.isPrototypeOf(baz)); // true“Object.prototype.isPrototypeOf() - JavaScript | MDN” (MDN Web Docs). Retrieved January 17, 2024.
Object.isSealed()
The Object.isSealed() static method determines if an object is sealed.
Syntax
Object.isSealed(obj)
Parameters
obj - The object which should be checked.Return value
A Boolean indicating whether or not the given object is sealed.
“Object.isSealed() - JavaScript | MDN” (MDN Web Docs). Retrieved January 18, 2024.
Object.keys()
The Object.keys() static method returns an array of a given object’s own enumerable string-keyed property names.
Syntax
Object.keys(obj)
Parameters
obj - An object.Return value
An array of strings representing the given object’s own enumerable string-keyed property keys.
Example
// Simple array
const arr = ["a", "b", "c"];
console.log(Object.keys(arr)); // ['0', '1', '2']
// Array-like object
const obj = { 0: "a", 1: "b", 2: "c" };
console.log(Object.keys(obj)); // ['0', '1', '2']
// Array-like object with random key ordering
const anObj = { 100: "a", 2: "b", 7: "c" };
console.log(Object.keys(anObj)); // ['2', '7', '100']
// getFoo is a non-enumerable property
const myObj = Object.create(
{},
{
getFoo: {
value() {
return this.foo;
},
},
},
);
myObj.foo = 1;
console.log(Object.keys(myObj)); // ['foo']“Object.keys() - JavaScript | MDN” (MDN Web Docs). Retrieved January 18, 2024.
Object.preventExtensions()
The Object.preventExtensions() static method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object’s prototype from being re-assigned.
Object.preventExtensions() only prevents addition of own properties. Properties can still be added to the object prototype.
Syntax
Object.preventExtensions(obj)
Parameters
obj - The object which should be made non-extensible.Return value
The object being made non-extensible.
Examples
// Object.preventExtensions returns the object
// being made non-extensible.
const obj = {};
const obj2 = Object.preventExtensions(obj);
obj === obj2; // true
// Objects are extensible by default.
const empty = {};
Object.isExtensible(empty); // true
// They can be made un-extensible
Object.preventExtensions(empty);
Object.isExtensible(empty); // false
// Object.defineProperty throws when adding
// a new property to a non-extensible object.
const nonExtensible = { removable: true };
Object.preventExtensions(nonExtensible);
Object.defineProperty(nonExtensible, "new", {
value: 8675309,
}); // throws a TypeError
// In strict mode, attempting to add new properties
// to a non-extensible object throws a TypeError.
function fail() {
"use strict";
// throws a TypeError
nonExtensible.newProperty = "FAIL";
}
fail();“Object.preventExtensions() - JavaScript | MDN” (MDN Web Docs). Retrieved January 18, 2024.