Objects API Flashcards

1
Q

Object constructor

A

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 is null or undefined, it creates and returns an empty object.
  • If the value is an object already, it returns the value.
  • Otherwise, it returns an object of a type that corresponds to the given value. For example, passing a bigInt primitive returns a BigInt wrapper object.
  • When 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Object.assign()

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Object.create()

A

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

  • 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 } });
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Object.defineProperties()

A

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

  • 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.
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Object.defineProperty()

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Object.entries()

A

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'] ]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Object.freeze()

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Object.fromEntries()

A

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 }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Object.getOwnPropertyDescriptor()

A

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

  • 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Object.getOwnPropertyDescriptors()

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Object.getOwnPropertyNames()

A

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"]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Object.getOwnPropertySymbols()

A

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)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Object.getPrototypeOf()

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Object.groupBy()

A

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 }
  ]
}
*/
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Object.hasOwn()

A

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 value
true 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Object.prototype.hasOwnProperty()

A

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
17
Q

What issues does Object.prototype.hasOwnProperty() have?

A

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 false

The 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 function

The solutions in this case are the same as for the previous section: use Object.hasOwn() by preference, otherwise use an external object’s hasOwnProperty().

18
Q

Object.is()

A

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
19
Q

Object.isExtensible()

A

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
20
Q

Object.isFrozen()

A

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
21
Q

Object.prototype.isPrototypeOf()

A

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
22
Q

Object.isSealed()

A

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.

23
Q

Object.keys()

A

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']
24
Q

Object.preventExtensions()

A

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();
25
Q

Object.prototype.propertyIsEnumerable()

A

The propertyIsEnumerable() method of Object instances returns a boolean indicating whether the specified property is this object’s enumerable own property.

Syntax

propertyIsEnumerable(prop)

Parameters

  • prop - The name of the property to test. Can be a string or a Symbol.

Return value

A boolean value indicating whether the specified property is enumerable and is the object’s own property.

26
Q

Object.seal()

A

The Object.seal() static method seals an object. Sealing an object prevents extensions and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. seal() returns the same object that was passed in.

The prototype chain remains untouched. However, due to the effect of preventing extensions, the [[Prototype]] cannot be reassigned.

Unlike Object.freeze(), objects sealed with Object.seal() may have their existing properties changed, as long as they are writable.

Syntax

Object.seal(obj)

Parameters

  • obj - The object which should be sealed.

Return value

The object being sealed.

Exceptions

  • TypeError - Thrown if the argument obj is not an object (a primitive).

Example

const obj = {
  prop() {},
  foo: "bar",
};

// New properties may be added, existing properties
// may be changed or removed.
obj.foo = "baz";
obj.lumpy = "woof";
delete obj.prop;

const o = Object.seal(obj);

o === obj; // true
Object.isSealed(obj); // true

// Changing property values on a sealed object
// still works.
obj.foo = "quux";

// But you can't convert data properties to accessors,
// or vice versa.
Object.defineProperty(obj, "foo", {
  get() {
    return "g";
  },
}); // throws a TypeError

// Now any changes, other than to property values,
// will fail.
obj.quaxxor = "the friendly duck";
// silently doesn't add the property
delete obj.foo;
// silently doesn't delete the property

// ...and in strict mode such attempts
// will throw TypeErrors.
function fail() {
  "use strict";
  delete obj.foo; // throws a TypeError
  obj.sparky = "arf"; // throws a TypeError
}
fail();

// Attempted additions through
// Object.defineProperty will also throw.
Object.defineProperty(obj, "ohai", {
  value: 17,
}); // throws a TypeError
Object.defineProperty(obj, "foo", {
  value: "eit",
}); // changes existing property value
27
Q

Object.setPrototypeOf()

A

The Object.setPrototypeOf() static method sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null.

Syntax

Object.setPrototypeOf(obj, prototype)

Parameters

  • obj - The object which is to have its prototype set.
  • prototype - The object’s new prototype (an object or null).

Return value
The specified object.

Exceptions

TypeError - Thrown in one of the following cases:

  • The obj parameter is undefined or null.
  • The obj parameter is non-extensible, or it’s an immutable prototype exotic object, such as Object.prototype or window. However, the error is not thrown if the new prototype is the same value as the original prototype of obj.
  • The prototype parameter is not an object or null.
28
Q

Object.prototype.toLocaleString()

A

The toLocaleString() method of Object instances returns a string representing this object. This method is meant to be overridden by derived objects for locale-specific purposes.

Syntax

toLocaleString()

Parameters

  • None. However, all objects that override this method are expected to accept at most two parameters, corresponding to locales and options, such as Date.prototype.toLocaleString. The parameter positions should not be used for any other purpose.

Return value

The return value of calling this.toString().

Examples:

/* Arrays */
const testArray = [4, 7, 10];

const euroPrices = testArray.toLocaleString("fr", {
  style: "currency",
  currency: "EUR",
});
// "4,00 €,7,00 €,10,00 €"

/* Dates */
const testDate = new Date();
// "Fri May 29 2020 18:04:24 GMT+0100 (British Summer Time)"

const deDate = testDate.toLocaleString("de");
// "29.5.2020, 18:04:24"

const frDate = testDate.toLocaleString("fr");
// "29/05/2020, 18:04:24"

/* Numbers */ 

const testNumber = 2901234564;
// "2901234564"

const deNumber = testNumber.toLocaleString("de");
// "2.901.234.564"

const frNumber = testNumber.toLocaleString("fr");
// "2 901 234 564"
29
Q

Object.prototype.toString()

A

The toString() method of Object instances returns a string representing this object. This method is meant to be overridden by derived objects for custom type coercion logic.

Syntax

toString()

Parameters
By default toString() takes no parameters. However, objects that inherit from Object may override it with their own implementations that do take parameters. For example, the Number.prototype.toString() and BigInt.prototype.toString() methods take an optional radix parameter.

Return value
A string representing the object.

30
Q

Object.prototype.valueOf()

A

The valueOf() method of Object instances converts the this value to an object. This method is meant to be overridden by derived objects for custom type conversion logic.

JavaScript calls the valueOf method to convert an object to a primitive value. You rarely need to invoke the valueOf method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.

Syntax

valueOf()

Parameters
None.

Return value
The this value, converted to an object.

Examples

const obj = { foo: 1 };
console.log(obj.valueOf() === obj); // true

console.log(Object.prototype.valueOf.call("primitive"));
// [String: 'primitive'] (a wrapper object)

// Overriding valueOf for custom objects
class Box {
  #value;
  constructor(value) {
    this.#value = value;
  }
  valueOf() {
    return this.#value;
  }
}

// We can now do number operations with Box instances
const box = new Box(123);
console.log(box + 456); // 579
console.log(box == 123); // true
31
Q

Object.values()

A

The Object.values() static method returns an array of a given object’s own enumerable string-keyed property values.

Syntax

Object.values(obj)

Parameters

  • obj - An object.

Return value
An array containing the given object’s own enumerable string-keyed property values.

Throws

  • TypeError - it throws a TypeError if the passed argument can not be coerced to an object.null and undefined will throw and error.

Example

const obj = { foo: "bar", baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]

// Array-like object
const arrayLikeObj1 = { 0: "a", 1: "b", 2: "c" };
console.log(Object.values(arrayLikeObj1)); // ['a', 'b', 'c']

// Array-like object with random key ordering
// When using numeric keys, the values are returned in the keys' numerical order
const arrayLikeObj2 = { 100: "a", 2: "b", 7: "c" };
console.log(Object.values(arrayLikeObj2)); // ['b', 'c', 'a']

// getFoo is a non-enumerable property
const myObj = Object.create(
  {},
  {
    getFoo: {
      value() {
        return this.foo;
      },
    },
  },
);
myObj.foo = "bar";
console.log(Object.values(myObj)); // ['bar']