Objects API Flashcards
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:
- If the
value
isnull
orundefined
, it creates and returns an empty object. - If the
value
is an object already, it returns thevalue
. - Otherwise, it returns an object of a type that corresponds to the given value. For example, passing a
bigInt
primitive returns aBigInt
wrapper object. - When
Object()
is constructed butnew.target
is not theObject
constructor itself, the behavior is slightly different — it initializes a new object withnew.target.prototype
as its prototype. Any argument value is ignored. This may happen, for example, whenObject()
is implicitly called viasuper()
in the constructor of aclass
that extendsObject
. In this case, even if you pass a number tosuper()
, the this value inside the constructor does not become aNumber
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 notundefined
, 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 ofObject.defineProperties()
.
Return value
- A new object with the specified prototype object and properties.
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 (seeObject.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 tofalse
. -
enumerable
-true
if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults tofalse
.
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 toundefined
. -
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 agetter
for the property, orundefined
if there is no getter. The function’s return value will be used as the value of the property. Defaults toundefined
. -
set
- A function which serves as asetter
for the property, orundefined
if there is no setter. The function will receive as its only argument the new value being assigned to the property. Defaults toundefined
.
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.
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 tofalse
. -
enumerable
-true
if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults tofalse
.
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 toundefined
. -
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 agetter
for the property, orundefined
if there is no getter. The function’s return value will be used as the value of the property. Defaults toundefined
. -
set
- A function which serves as asetter
for the property, orundefined
if there is no setter. The function will receive as its only argument the new value being assigned to the property. Defaults toundefined
.
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
- A new object whose properties are given by the entries of the iterable.
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 orSymbol
of the property whose description is to be retrieved.
Return value
- A property descriptor of the given property if it exists on the object,
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
- An object containing all own property descriptors of an object. Might be an empty object, if there are no properties.
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
- An array of strings that corresponds to the properties found directly in the given object.
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
- The prototype of the given object, which may be
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.