Object.prototype.__defineSetter__() - JavaScript

Object.prototype.\_\_defineSetter\_\_()
=======================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Note:** This feature is deprecated in favor of defining setters using the object initializer syntax or the `Object.defineProperty()` API. This method's behavior is only specified for web compatibility, and is not required to be implemented in any platform. It may not work everywhere.

The **`__defineSetter__()`** method of `Object` instances binds an object's property to a function to be called when an attempt is made to set that property.

Syntax
------

```js
\_\_defineSetter\_\_(prop, func)
```

### Parameters

`prop`

A string containing the name of the property that the setter `func` is bound to.

`func`

A function to be called when there is an attempt to set the specified property. This function receives the following parameter:

`val`

The value attempted to be assigned to `prop`.

### Return value

None (`undefined`).

### Exceptions

`TypeError`

Thrown if `func` is not a function.

Description
-----------

All objects that inherit from `Object.prototype` (that is, all except `null`-prototype objects) inherit the `__defineSetter__()` method. This method allows a setter to be defined on a pre-existing object. This is equivalent to `Object.defineProperty(obj, prop, { set: func, configurable: true, enumerable: true })`, which means the property is enumerable and configurable, and any existing getter, if present, is preserved.

`__defineSetter__()` is defined in the spec as "normative optional", which means no implementation is required to implement this. However, all major browsers implement it, and due to its continued usage, it's unlikely to be removed. If a browser implements `__defineSetter__()`, it also needs to implement the `__lookupGetter__()`, `__lookupSetter__()`, and `__defineGetter__()` methods.

Examples
--------

### Using \_\_defineSetter\_\_()

```js
const o = {};
o.\_\_defineSetter\_\_("value", function (val) {
  this.anotherValue = val;
});
o.value = 5;
console.log(o.value); // undefined
console.log(o.anotherValue); // 5
```

### Defining a setter property in standard ways

You can use the `set` syntax to define a setter when the object is first initialized.

```js
const o = {
  set value(val) {
    this.anotherValue = val;
  },
};
o.value = 5;
console.log(o.value); // undefined
console.log(o.anotherValue); // 5
```

You may also use `Object.defineProperty()` to define a setter on an object after it's been created. Compared to `__defineSetter__()`, this method allows you to control the setter's enumerability and configurability, as well as defining symbol properties. The `Object.defineProperty()` method also works with `null`-prototype objects, which don't inherit from `Object.prototype` and therefore don't have the `__defineSetter__()` method.

```js
const o = {};
Object.defineProperty(o, "value", {
  set(val) {
    this.anotherValue = val;
  },
  configurable: true,
  enumerable: true,
});
o.value = 5;
console.log(o.value); // undefined
console.log(o.anotherValue); // 5
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.prototype.\_\_defineSetter\_\_ |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Object.prototype.__defineSetter__` in `core-js`
* `Object.prototype.__defineGetter__()`
* `set`
* `Object.defineProperty()`
* `Object.prototype.__lookupGetter__()`
* `Object.prototype.__lookupSetter__()`
* JS Guide: Defining Getters and Setters
* Firefox bug 647423


Object.hasOwn() - JavaScript

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`.

**Note:** `Object.hasOwn()` is intended as a replacement for `Object.prototype.hasOwnProperty()`.

Try it
------

Syntax
------

```js
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`

Description
-----------

 The **`Object.hasOwn()`** method returns `true` if the specified property is a
 direct property of the object — even if the property value is `null` or `undefined`.
 The method returns `false` if the property is inherited, or has not been declared at all.
 Unlike the `in` operator, this
 method does not check for the specified property in the object's prototype chain.

 It is recommended over `Object.prototype.hasOwnProperty()` because
 it works for `null`-prototype objects and with objects that
 have overridden the inherited `hasOwnProperty()` method. While it is possible to
 workaround these problems by calling `Object.prototype.hasOwnProperty()` on an
 external object, `Object.hasOwn()` is more intuitive.

Examples
--------

### Using hasOwn to test for a property's existence

The following code shows how to determine whether the `example` object contains a property named `prop`.

```js
const example = {};
Object.hasOwn(example, "prop"); // false - 'prop' has not been defined

example.prop = "exists";
Object.hasOwn(example, "prop"); // true - 'prop' has been defined

example.prop = null;
Object.hasOwn(example, "prop"); // true - own property exists with value of null

example.prop = undefined;
Object.hasOwn(example, "prop"); // true - own property exists with value of undefined
```

### Direct vs. inherited properties

The following example differentiates between direct properties and properties inherited through the prototype chain:

```js
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
```

### Iterating over the properties of an object

To iterate over the enumerable properties of an object, you *should* use:

```js
const example = { foo: true, bar: true };
for (const name of Object.keys(example)) {
  // …
}
```

But if you need to use `for...in`, you can use `Object.hasOwn()` to skip the inherited properties:

```js
const example = { foo: true, bar: true };
for (const name in example) {
  if (Object.hasOwn(example, name)) {
    // …
  }
}
```

### Checking if an Array index exists

 The elements of an `Array` are defined as direct properties, so
 you can use `hasOwn()` method to check whether a particular index exists:

```js
const fruits = ["Apple", "Banana", "Watermelon", "Orange"];
Object.hasOwn(fruits, 3); // true ('Orange')
Object.hasOwn(fruits, 4); // false - not defined
```

### Problematic cases for hasOwnProperty

 This section demonstrates that `hasOwn()` is immune to the problems that affect
 `hasOwnProperty`. Firstly, it can be used with objects that have reimplemented
 `hasOwnProperty()`:

```js
const foo = {
  hasOwnProperty() {
    return false;
  },
  bar: "The dragons be out of office",
};

if (Object.hasOwn(foo, "bar")) {
  console.log(foo.bar); // true - re-implementation of hasOwnProperty() does not affect Object
}
```

 It can also be used with `null`-prototype objects. These do
 not inherit from `Object.prototype`, and so `hasOwnProperty()` is inaccessible.

```js
const foo = Object.create(null);
foo.prop = "exists";
if (Object.hasOwn(foo, "prop")) {
  console.log(foo.prop); // true - works irrespective of how the object is created.
}
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.hasown |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Object.hasOwn` in `core-js`
* `Object.prototype.hasOwnProperty()`
* Enumerability and ownership of properties
* `Object.getOwnPropertyNames()`
* `for...in`
* `in`
* Inheritance and the prototype chain


Object.keys() - JavaScript

Object.keys()
=============

The **`Object.keys()`** static method returns an array of a given object's own enumerable string-keyed property names.

Try it
------

Syntax
------

```js
Object.keys(obj)
```

### Parameters

`obj`

An object.

### Return value

An array of strings representing the given object's own enumerable string-keyed property keys.

Description
-----------

`Object.keys()` returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.keys()` is the same as that provided by a `for...in` loop.

If you need the property values, use `Object.values()` instead. If you need both the property keys and values, use `Object.entries()` instead.

Examples
--------

### Using Object.keys()

```js
// 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']
```

If you want *all* string-keyed own properties, including non-enumerable ones, see `Object.getOwnPropertyNames()`.

### Using Object.keys() on primitives

Non-object arguments are coerced to objects. `undefined` and `null` cannot be coerced to objects and throw a `TypeError` upfront. Only strings may have own enumerable properties, while all other primitives return an empty array.

```js
// Strings have indices as enumerable own properties
console.log(Object.keys("foo")); // ['0', '1', '2']

// Other primitives except undefined and null have no own properties
console.log(Object.keys(100)); // []
```

**Note:** In ES5, passing a non-object to `Object.keys()` threw a `TypeError`.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.keys |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Object.keys` in `core-js`
* Enumerability and ownership of properties
* `Object.entries()`
* `Object.values()`
* `Object.prototype.propertyIsEnumerable()`
* `Object.create()`
* `Object.getOwnPropertyNames()`
* `Map.prototype.keys()`


Object.isSealed() - JavaScript

Object.isSealed()
=================

 The **`Object.isSealed()`** static method determines if an object is
 sealed.

Try it
------

Syntax
------

```js
Object.isSealed(obj)
```

### Parameters

`obj`

The object which should be checked.

### Return value

A `Boolean` indicating whether or not the given object is sealed.

Description
-----------

 Returns `true` if the object is sealed, otherwise `false`. An
 object is sealed if it is not extensible and
 if all its properties are non-configurable and therefore not removable (but not
 necessarily non-writable).

Examples
--------

### Using Object.isSealed

```js
// Objects aren't sealed by default.
const empty = {};
Object.isSealed(empty); // false

// If you make an empty object non-extensible,
// it is vacuously sealed.
Object.preventExtensions(empty);
Object.isSealed(empty); // true

// The same is not true of a non-empty object,
// unless its properties are all non-configurable.
const hasProp = { fee: "fie foe fum" };
Object.preventExtensions(hasProp);
Object.isSealed(hasProp); // false

// But make them all non-configurable
// and the object becomes sealed.
Object.defineProperty(hasProp, "fee", {
  configurable: false,
});
Object.isSealed(hasProp); // true

// The easiest way to seal an object, of course,
// is Object.seal.
const sealed = {};
Object.seal(sealed);
Object.isSealed(sealed); // true

// A sealed object is, by definition, non-extensible.
Object.isExtensible(sealed); // false

// A sealed object might be frozen,
// but it doesn't have to be.
Object.isFrozen(sealed); // true
// (all properties also non-writable)

const s2 = Object.seal({ p: 3 });
Object.isFrozen(s2); // false
// ('p' is still writable)

const s3 = Object.seal({
  get p() {
    return 0;
  },
});
Object.isFrozen(s3); // true
// (only configurability matters for accessor properties)
```

### Non-object argument

In ES5, if the argument to this method is not an object (a primitive), then it will cause a `TypeError`. In ES2015, it will return `true` without any errors if a non-object argument is passed, since primitives are, by definition, immutable.

```js
Object.isSealed(1);
// TypeError: 1 is not an object (ES5 code)

Object.isSealed(1);
// true (ES2015 code)
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.issealed |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Object.seal()`
* `Object.preventExtensions()`
* `Object.isExtensible()`
* `Object.freeze()`
* `Object.isFrozen()`


Object.getPrototypeOf() - JavaScript

Object.getPrototypeOf()
=======================

 The **`Object.getPrototypeOf()`** static method returns the prototype
 (i.e. the value of the internal `[[Prototype]]` property) of the specified
 object.

Try it
------

Syntax
------

```js
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`.

Examples
--------

### Using getPrototypeOf

```js
const proto = {};
const obj = Object.create(proto);
Object.getPrototypeOf(obj) === proto; // true
```

### 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`.

```js
Object.getPrototypeOf("foo");
// TypeError: "foo" is not an object (ES5 code)
Object.getPrototypeOf("foo");
// String.prototype (ES2015 code)
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.getprototypeof |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Object.getPrototypeOf` in `core-js`
* `Object.prototype.isPrototypeOf()`
* `Object.setPrototypeOf()`
* `Object.prototype.__proto__`
* `Reflect.getPrototypeOf()`
* Object.getPrototypeOf by John Resig (2008)


Object.create() - JavaScript

Object.create()
===============

The **`Object.create()`** static method creates a new object, using an existing object as the prototype of the newly created object.

Try it
------

Syntax
------

```js
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`.

Examples
--------

### Classical inheritance with Object.create()

Below is an example of how to use `Object.create()` to achieve classical inheritance. This is for a single inheritance, which is all that JavaScript supports.

```js
// Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

// superclass method
Shape.prototype.move = function (x, y) {
  this.x += x;
  this.y += y;
  console.info("Shape moved.");
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype, {
  // If you don't set Rectangle.prototype.constructor to Rectangle,
  // it will take the prototype.constructor of Shape (parent).
  // To avoid that, we set the prototype.constructor to Rectangle (child).
  constructor: {
    value: Rectangle,
    enumerable: false,
    writable: true,
    configurable: true,
  },
});

const rect = new Rectangle();

console.log("Is rect an instance of Rectangle?", rect instanceof Rectangle); // true
console.log("Is rect an instance of Shape?", rect instanceof Shape); // true
rect.move(1, 1); // Logs 'Shape moved.'
```

Note that there are caveats to watch out for using `create()`, such as re-adding the `constructor` property to ensure proper semantics. Although `Object.create()` is believed to have better performance than mutating the prototype with `Object.setPrototypeOf()`, the difference is in fact negligible if no instances have been created and property accesses haven't been optimized yet. In modern code, the class syntax should be preferred in any case.

### Using propertiesObject argument with Object.create()

`Object.create()` allows fine-tuned control over the object creation process. The object initializer syntax is, in fact, a syntax sugar of `Object.create()`. With `Object.create()`, we can create objects with a designated prototype and also some properties. Note that the second parameter maps keys to *property descriptors* — this means you can control each property's enumerability, configurability, etc. as well, which you can't do in object initializers.

```js
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 } });
```

With `Object.create()`, we can create an object with `null` as prototype. The equivalent syntax in object initializers would be the `__proto__` key.

```js
o = Object.create(null);
// Is equivalent to:
o = { \_\_proto\_\_: null };
```

By default properties are *not* writable, enumerable or configurable.

```js
o.p = 24; // throws in strict mode
o.p; // 42

o.q = 12;
for (const prop in o) {
  console.log(prop);
}
// 'q'

delete o.p;
// false; throws in strict mode
```

To specify a property with the same attributes as in an initializer, explicitly specify `writable`, `enumerable` and `configurable`.

```js
o2 = Object.create(
  {},
  {
    p: {
      value: 42,
      writable: true,
      enumerable: true,
      configurable: true,
    },
  },
);
// This is not equivalent to:
// o2 = Object.create({ p: 42 })
// which will create an object with prototype { p: 42 }
```

You can use `Object.create()` to mimic the behavior of the `new` operator.

```js
function Constructor() {}
o = new Constructor();
// Is equivalent to:
o = Object.create(Constructor.prototype);
```

Of course, if there is actual initialization code in the `Constructor` function, the `Object.create()` method cannot reflect it.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.create |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Object.create` in `core-js`
* `Object.defineProperty()`
* `Object.defineProperties()`
* `Object.prototype.isPrototypeOf()`
* `Reflect.construct()`
* Object.getPrototypeOf by John Resig (2008)


Object.getOwnPropertySymbols() - JavaScript

Object.getOwnPropertySymbols()
==============================

The **`Object.getOwnPropertySymbols()`** static method returns an array of all symbol properties found directly upon a given object.

Try it
------

Syntax
------

```js
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.

Description
-----------

Similar to `Object.getOwnPropertyNames()`, you can get all symbol properties of a given object as an array of symbols. Note that `Object.getOwnPropertyNames()` itself does not contain the symbol properties of an object and only the string properties.

As all objects have no own symbol properties initially, `Object.getOwnPropertySymbols()` returns an empty array unless you have set symbol properties on your object.

Examples
--------

### Using Object.getOwnPropertySymbols()

```js
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)
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.getownpropertysymbols |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Object.getOwnPropertySymbols` in `core-js`
* `Object.getOwnPropertyNames()`
* `Symbol`


Object.freeze() - JavaScript

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.

Try it
------

Syntax
------

```js
Object.freeze(obj)
```

### Parameters

`obj`

The object to freeze.

### Return value

The object that was passed to the function.

Description
-----------

Freezing an object is equivalent to preventing extensions and then changing all existing properties' descriptors' `configurable` to `false` — and for data properties, `writable` to `false` as well. Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a `TypeError` exception (most commonly, but not exclusively, when in strict mode).

 For data properties of a frozen object, their values cannot be changed since the `writable` and
 `configurable` attributes are set to `false`. Accessor properties (getters and setters) work the same — the property value returned by the getter may still change, and the setter can still be called without throwing errors when setting the property. Note that values
 that are objects can still be modified, unless they are also frozen. As an object, an
 array can be frozen; after doing so, its elements cannot be altered and no elements can
 be added to or removed from the array.

Private properties do not have the concept of property descriptors. Freezing an object with private properties does not prevent the values of these private properties from being changed. (Freezing objects is usually meant as a security measure against external code, but external code cannot access private properties anyway.) Private properties cannot be added or removed from the object, whether the object is frozen or not.

`freeze()` returns the same object that was passed into the function. It
 *does not* create a frozen copy.

 A `TypedArray` or a `DataView` with elements will cause a `TypeError`,
 as they are views over memory and will definitely cause other possible issues:

```js
Object.freeze(new Uint8Array(0)); // No elements
// Uint8Array []

Object.freeze(new Uint8Array(1)); // Has elements
// TypeError: Cannot freeze array buffer views with elements

Object.freeze(new DataView(new ArrayBuffer(32))); // No elements
// DataView {}

Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)); // No elements
// Float64Array []

Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)); // Has elements
// TypeError: Cannot freeze array buffer views with elements
```

 Note that as the standard three properties (`buf.byteLength`,
 `buf.byteOffset` and `buf.buffer`) are read-only (as are those of
 an `ArrayBuffer` or `SharedArrayBuffer`), there is no reason for
 attempting to freeze these properties.

Unlike `Object.seal()`, existing properties in objects frozen with `Object.freeze()` are made immutable and data properties cannot be re-assigned.

Examples
--------

### Freezing objects

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

// Before freezing: new properties may be added,
// and existing properties may be changed or removed
obj.foo = "baz";
obj.lumpy = "woof";
delete obj.prop;

// Freeze.
const o = Object.freeze(obj);

// The return value is just the same object we passed in.
o === obj; // true

// The object has become frozen.
Object.isFrozen(obj); // === true

// Now any changes will fail
obj.foo = "quux"; // silently does nothing
// silently doesn't add the property
obj.quaxxor = "the friendly duck";

// In strict mode such attempts will throw TypeErrors
function fail() {
  "use strict";
  obj.foo = "sparky"; // throws a TypeError
  delete obj.foo; // throws a TypeError
  delete obj.quaxxor; // returns true since attribute 'quaxxor' was never added
  obj.sparky = "arf"; // throws a TypeError
}

fail();

// Attempted changes through Object.defineProperty;
// both statements below throw a TypeError.
Object.defineProperty(obj, "ohai", { value: 17 });
Object.defineProperty(obj, "foo", { value: "eit" });

// It's also impossible to change the prototype
// both statements below will throw a TypeError.
Object.setPrototypeOf(obj, { x: 20 });
obj.__proto__ = { x: 20 };
```

### Freezing arrays

```js
const a = [0];
Object.freeze(a); // The array cannot be modified now.

a[0] = 1; // fails silently

// In strict mode such attempt will throw a TypeError
function fail() {
  "use strict";
  a[0] = 1;
}

fail();

// Attempted to push
a.push(2); // throws a TypeError
```

 The object being frozen is *immutable*. However, it is not necessarily
 *constant*. The following example shows that a frozen object is not constant
 (freeze is shallow).

```js
const obj1 = {
  internal: {},
};

Object.freeze(obj1);
obj1.internal.a = "aValue";

obj1.internal.a; // 'aValue'
```

 To be a constant object, the entire reference graph (direct and indirect references to
 other objects) must reference only immutable frozen objects. The object being frozen is
 said to be immutable because the entire object *state* (values and references to
 other objects) within the whole object is fixed. Note that strings, numbers, and
 booleans are always immutable and that Functions and Arrays are objects.

#### What is "shallow freeze"?

 The result of calling `Object.freeze(object)` only applies to the
 immediate properties of `object` itself and will prevent future property
 addition, removal or value re-assignment operations *only* on
 `object`. If the value of those properties are objects themselves, those
 objects are not frozen and may be the target of property addition, removal or value
 re-assignment operations.

```js
const employee = {
  name: "Mayank",
  designation: "Developer",
  address: {
    street: "Rohini",
    city: "Delhi",
  },
};

Object.freeze(employee);

employee.name = "Dummy"; // fails silently in non-strict mode
employee.address.city = "Noida"; // attributes of child object can be modified

console.log(employee.address.city); // "Noida"
```

 To make an object immutable, recursively freeze each non-primitive property
 (deep freeze). Use the pattern on a case-by-case basis based on your design when you
 know the object contains no cycles in the reference
 graph, otherwise an endless loop will be triggered. An enhancement to
 `deepFreeze()` would be to have an internal function that receives a path
 (e.g. an Array) argument so you can suppress calling `deepFreeze()`
 recursively when an object is in the process of being made immutable. You still run a
 risk of freezing an object that shouldn't be frozen, such as `window`.

```js
function deepFreeze(object) {
  // Retrieve the property names defined on object
  const propNames = Reflect.ownKeys(object);

  // Freeze properties before freezing self
  for (const name of propNames) {
    const value = object[name];

    if ((value && typeof value === "object") || typeof value === "function") {
      deepFreeze(value);
    }
  }

  return Object.freeze(object);
}

const obj2 = {
  internal: {
    a: null,
  },
};

deepFreeze(obj2);

obj2.internal.a = "anotherValue"; // fails silently in non-strict mode
obj2.internal.a; // null
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.freeze |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Object.isFrozen()`
* `Object.preventExtensions()`
* `Object.isExtensible()`
* `Object.seal()`
* `Object.isSealed()`


Object() constructor - JavaScript

Object() constructor
====================

The **`Object()`** constructor turns the input into an object. Its behavior depends on the input's type.

Syntax
------

```js
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.

Examples
--------

### Creating a new Object

```js
const o = new Object();
o.foo = 42;

console.log(o);
// { foo: 42 }
```

### Using Object given undefined and null types

The following examples store an empty `Object` object in `o`:

```js
const o = new Object();
```

```js
const o = new Object(undefined);
```

```js
const o = new Object(null);
```

### Obtaining wrapper objects for BigInt and Symbol

The `BigInt()` and `Symbol()` constructors throw an error when called with `new`, to prevent the common mistake of creating a wrapper object instead of the primitive value. The only way to create a wrapper object for these types is to call `Object()` with them:

```js
const numberObj = new Number(1);
console.log(typeof numberObj); // "object"

const bigintObj = Object(1n);
console.log(typeof bigintObj); // "object"

const symbolObj = Object(Symbol("foo"));
console.log(typeof symbolObj); // "object"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object-constructor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Object initializer


Object.seal() - JavaScript

Object.seal()
=============

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.

Try it
------

Syntax
------

```js
Object.seal(obj)
```

### Parameters

`obj`

The object which should be sealed.

### Return value

The object being sealed.

Description
-----------

 Sealing an object is equivalent to preventing extensions and then changing all existing properties' descriptors to `configurable: false`. This has the effect of making the set of properties on the object fixed. Making all properties non-configurable
 also prevents them from being converted from data properties to accessor properties and
 vice versa, but it does not prevent the values of data properties from being changed.
 Attempting to delete or add properties to a sealed object, or to convert a data property
 to accessor or vice versa, will fail, either silently or by throwing a
 `TypeError` (most commonly, although not exclusively, when in
 strict mode code).

Private properties do not have the concept of property descriptors. Private properties cannot be added or removed from the object, whether the object is sealed or not.

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.

Examples
--------

### Using Object.seal

```js
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
```

### Non-object argument

In ES5, if the argument to this method is not an object (a primitive), then it will cause a `TypeError`. In ES2015, a non-object argument will be returned as-is without any errors, since primitives are already, by definition, immutable.

```js
Object.seal(1);
// TypeError: 1 is not an object (ES5 code)

Object.seal(1);
// 1 (ES2015 code)
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.seal |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Object.isSealed()`
* `Object.preventExtensions()`
* `Object.isExtensible()`
* `Object.freeze()`
* `Object.isFrozen()`


Object.prototype.propertyIsEnumerable() - JavaScript

Object.prototype.propertyIsEnumerable()
=======================================

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

Try it
------

Syntax
------

```js
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.

Description
-----------

All objects that inherit from `Object.prototype` (that is, all except `null`-prototype objects) inherit the `propertyIsEnumerable()` method. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns `false`.

This method is equivalent to `Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false`.

Examples
--------

### Using propertyIsEnumerable()

The following example shows the use of `propertyIsEnumerable()` on objects and arrays.

```js
const o = {};
const a = [];
o.prop = "is enumerable";
a[0] = "is enumerable";

o.propertyIsEnumerable("prop"); // true
a.propertyIsEnumerable(0); // true
```

### User-defined vs. built-in objects

Most built-in properties are non-enumerable by default, while user-created object properties are often enumerable, unless explicitly designated otherwise.

```js
const a = ["is enumerable"];

a.propertyIsEnumerable(0); // true
a.propertyIsEnumerable("length"); // false

Math.propertyIsEnumerable("random"); // false
globalThis.propertyIsEnumerable("Math"); // false
```

### Direct vs. inherited properties

Only enumerable own properties cause `propertyIsEnumerable()` to return `true`, although all enumerable properties, including inherited ones, are visited by the `for...in` loop.

```js
const o1 = {
  enumerableInherited: "is enumerable",
};
Object.defineProperty(o1, "nonEnumerableInherited", {
  value: "is non-enumerable",
  enumerable: false,
});
const o2 = {
  // o1 is the prototype of o2
  \_\_proto\_\_: o1,
  enumerableOwn: "is enumerable",
};
Object.defineProperty(o2, "nonEnumerableOwn", {
  value: "is non-enumerable",
  enumerable: false,
});

o2.propertyIsEnumerable("enumerableInherited"); // false
o2.propertyIsEnumerable("nonEnumerableInherited"); // false
o2.propertyIsEnumerable("enumerableOwn"); // true
o2.propertyIsEnumerable("nonEnumerableOwn"); // false
```

### Testing symbol properties

`Symbol` properties are also supported by `propertyIsEnumerable()`. Note that most enumeration methods only visit string properties; enumerability of symbol properties is only useful when using `Object.assign()` or spread syntax. For more information, see Enumerability and ownership of properties.

```js
const sym = Symbol("enumerable");
const sym2 = Symbol("non-enumerable");
const o = {
  [sym]: "is enumerable",
};
Object.defineProperty(o, sym2, {
  value: "is non-enumerable",
  enumerable: false,
});

o.propertyIsEnumerable(sym); // true
o.propertyIsEnumerable(sym2); // false
```

### Usage with null-prototype objects

Because `null`-prototype objects do not inherit from `Object.prototype`, they do not inherit the `propertyIsEnumerable()` method. You must call `Object.prototype.propertyIsEnumerable` with the object as `this` instead.

```js
const o = {
  \_\_proto\_\_: null,
  enumerableOwn: "is enumerable",
};

o.propertyIsEnumerable("enumerableOwn"); // TypeError: o.propertyIsEnumerable is not a function
Object.prototype.propertyIsEnumerable.call(o, "enumerableOwn"); // true
```

Alternatively, you may use `Object.getOwnPropertyDescriptor()` instead, which also helps to distinguish between non-existent properties and actually non-enumerable properties.

```js
const o = {
  \_\_proto\_\_: null,
  enumerableOwn: "is enumerable",
};

Object.getOwnPropertyDescriptor(o, "enumerableOwn")?.enumerable; // true
Object.getOwnPropertyDescriptor(o, "nonExistent")?.enumerable; // undefined
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.prototype.propertyisenumerable |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Enumerability and ownership of properties
* `for...in`
* `Object.keys()`
* `Object.defineProperty()`


Object.prototype.valueOf() - JavaScript

Object.prototype.valueOf()
==========================

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.

Try it
------

Syntax
------

```js
valueOf()
```

### Parameters

None.

### Return value

The `this` value, converted to an object.

**Note:** In order for `valueOf` to be useful during type conversion, it must return a primitive. Because all primitive types have their own `valueOf()` methods, calling `aPrimitiveValue.valueOf()` generally does not invoke `Object.prototype.valueOf()`.

Description
-----------

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.

This method is called in priority by numeric conversion and primitive conversion, but string conversion calls `toString()` in priority, and `toString()` is very likely to return a string value (even for the `Object.prototype.toString()` base implementation), so `valueOf()` is usually not called in this case.

All objects that inherit from `Object.prototype` (that is, all except `null`-prototype objects) inherit the `toString()` method. The `Object.prototype.valueOf()` base implementation is deliberately useless: by returning an object, its return value will never be used by any primitive conversion algorithm. Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override `valueOf()` to call a custom method, so that your custom object can be converted to a primitive value. Generally, `valueOf()` is used to return a value that is most meaningful for the object — unlike `toString()`, it does not need to be a string. Alternatively, you can add a `@@toPrimitive` method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion.

Examples
--------

### Using valueOf()

The base `valueOf()` method returns the `this` value itself, converted to an object if it isn't already. Therefore its return value will never be used by any primitive conversion algorithm.

```js
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

You can create a function to be called in place of the default `valueOf` method. Your function should take no arguments, since it won't be passed any when called during type conversion.

For example, you can add a `valueOf` method to your custom class `Box`.

```js
class Box {
  #value;
  constructor(value) {
    this.#value = value;
  }
  valueOf() {
    return this.#value;
  }
}
```

With the preceding code in place, any time an object of type `Box` is used in a context where it is to be represented as a primitive value (but not specifically a string), JavaScript automatically calls the function defined in the preceding code.

```js
const box = new Box(123);
console.log(box + 456); // 579
console.log(box == 123); // true
```

An object's `valueOf` method is usually invoked by JavaScript, but you can invoke it yourself as follows:

```js
box.valueOf();
```

### Using unary plus on objects

Unary plus performs number coercion on its operand, which, for most objects without `@@toPrimitive`, means calling its `valueOf()`. However, if the object doesn't have a custom `valueOf()` method, the base implementation will cause `valueOf()` to be ignored and the return value of `toString()` to be used instead.

```js
+new Date(); // the current timestamp; same as new Date().getTime()
+{}; // NaN (toString() returns "[object Object]")
+[]; // 0 (toString() returns an empty string list)
+[1]; // 1 (toString() returns "1")
+[1, 2]; // NaN (toString() returns "1,2")
+new Set([1]); // NaN (toString() returns "[object Set]")
+{ valueOf: () => 42 }; // 42
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.prototype.valueof |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Object.prototype.toString()`
* `parseInt()`
* `Symbol.toPrimitive`


Object.prototype.__lookupGetter__() - JavaScript

Object.prototype.\_\_lookupGetter\_\_()
=======================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Note:** This feature is deprecated in favor of the `Object.getOwnPropertyDescriptor()` API. This method's behavior is only specified for web compatibility, and is not required to be implemented in any platform. It may not work everywhere.

The **`__lookupGetter__()`** method of `Object` instances returns the function bound as a getter to the specified property.

Syntax
------

```js
\_\_lookupGetter\_\_(prop)
```

### Parameters

`prop`

A string containing the name of the property whose getter should be returned.

### Return value

The function bound as a getter to the specified property. Returns `undefined` if no such property is found, or the property is a data property.

Description
-----------

All objects that inherit from `Object.prototype` (that is, all except `null`-prototype objects) inherit the `__lookupGetter__()` method. If a getter has been defined for an object's property, it's not possible to reference the getter function through that property, because that property refers to the return value of that function. `__lookupGetter__()` can be used to obtain a reference to the getter function.

`__lookupGetter__()` walks up the prototype chain to find the specified property. If any object along the prototype chain has the specified own property, the `get` attribute of the property descriptor for that property is returned. If that property is a data property, `undefined` is returned. If the property is not found along the entire prototype chain, `undefined` is also returned.

`__lookupGetter__()` is defined in the spec as "normative optional", which means no implementation is required to implement this. However, all major browsers implement it, and due to its continued usage, it's unlikely to be removed. If a browser implements `__lookupGetter__()`, it also needs to implement the `__lookupSetter__()`, `__defineGetter__()`, and `__defineSetter__()` methods.

Examples
--------

### Using \_\_lookupGetter\_\_()

```js
const obj = {
  get foo() {
    return Math.random() > 0.5 ? "foo" : "bar";
  },
};

obj.\_\_lookupGetter\_\_("foo");
// [Function: get foo]
```

### Looking up a property's getter in the standard way

You should use the `Object.getOwnPropertyDescriptor()` API to look up a property's getter. Compared to `__lookupGetter__()`, this method allows looking up symbol properties. The `Object.getOwnPropertyDescriptor()` method also works with `null`-prototype objects, which don't inherit from `Object.prototype` and therefore don't have the `__lookupGetter__()` method. If `__lookupGetter__()`'s behavior of walking up the prototype chain is important, you may implement it yourself with `Object.getPrototypeOf()`.

```js
const obj = {
  get foo() {
    return Math.random() > 0.5 ? "foo" : "bar";
  },
};

Object.getOwnPropertyDescriptor(obj, "foo").get;
// [Function: get foo]
```

```js
const obj2 = {
  \_\_proto\_\_: {
    get foo() {
      return Math.random() > 0.5 ? "foo" : "bar";
    },
  },
};

function findGetter(obj, prop) {
  while (obj) {
    const desc = Object.getOwnPropertyDescriptor(obj, prop);
    if (desc) {
      return desc.get;
    }
    obj = Object.getPrototypeOf(obj);
  }
}

console.log(findGetter(obj2, "foo")); // [Function: get foo]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.prototype.\_\_lookupGetter\_\_ |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Object.prototype.__lookupGetter__` in `core-js`
* `Object.prototype.__lookupSetter__()`
* `get`
* `Object.getOwnPropertyDescriptor()`
* `Object.prototype.__defineGetter__()`
* `Object.prototype.__defineSetter__()`
* JS Guide: Defining Getters and Setters


Object.prototype.hasOwnProperty() - JavaScript

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.

Try it
------

Syntax
------

```js
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.

Description
-----------

 The **`hasOwnProperty()`** method returns `true` if the specified property is a
 direct property of the object — even if the value is `null` or `undefined`. The
 method returns `false` if the property is inherited, or has not been declared at
 all. Unlike the `in` operator, this
 method does not check for the specified property in the object's prototype
 chain.

 The method can be called on *most* JavaScript objects, because most objects
 descend from `Object`, and hence inherit its methods. For
 example `Array` is an `Object`, so you can
 use `hasOwnProperty()` method to check whether an index exists:

```js
const fruits = ["Apple", "Banana", "Watermelon", "Orange"];
fruits.hasOwnProperty(3); // true ('Orange')
fruits.hasOwnProperty(4); // false - not defined
```

 The method will not be available in objects where it is reimplemented, or on
 `null`-prototype objects (as these don't inherit from
 `Object.prototype`). Examples for these cases are given below.

Examples
--------

### Using hasOwnProperty to test for an own property's existence

The following code shows how to determine whether the `example` object contains a property named `prop`.

```js
const example = {};
example.hasOwnProperty("prop"); // false

example.prop = "exists";
example.hasOwnProperty("prop"); // true - 'prop' has been defined

example.prop = null;
example.hasOwnProperty("prop"); // true - own property exists with value of null

example.prop = undefined;
example.hasOwnProperty("prop"); // true - own property exists with value of undefined
```

### Direct vs. inherited properties

The following example differentiates between direct properties and properties inherited through the prototype chain:

```js
const example = {};
example.prop = "exists";

// `hasOwnProperty` will only return true for direct properties:
example.hasOwnProperty("prop"); // true
example.hasOwnProperty("toString"); // false
example.hasOwnProperty("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
```

### Iterating over the properties of an object

 The following example shows how to iterate over the enumerable properties of an
 object without executing on inherited properties.

```js
const buz = {
  fog: "stack",
};

for (const name in buz) {
  if (buz.hasOwnProperty(name)) {
    console.log(`this is fog (${name}) for sure. Value: ${buz[name]}`);
  } else {
    console.log(name); // toString or something else
  }
}
```

 Note that the `for...in` loop
 only iterates enumerable items: the absence of non-enumerable properties emitted
 from the loop does not imply that `hasOwnProperty` itself is confined strictly
 to enumerable items. You can iterate over non-enumerable properties with
 `Object.getOwnPropertyNames()`.

### 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:

```js
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`:

```js
const foo = { bar: "Here be dragons" };

// Use Object.hasOwn() method - recommended
Object.hasOwn(foo, "bar"); // true

// Use the hasOwnProperty property from the Object prototype
Object.prototype.hasOwnProperty.call(foo, "bar"); // true

// Use another Object's hasOwnProperty
// and call it with 'this' set to foo
({}).hasOwnProperty.call(foo, "bar"); // true
```

Note that in the first two cases there are no newly created objects.

### Objects created with Object.create(null)

`null`-prototype objects do not
 inherit from `Object.prototype`, making `hasOwnProperty()` inaccessible.

```js
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()`.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.prototype.hasownproperty |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Object.hasOwn()`
* Enumerability and ownership of properties
* `Object.getOwnPropertyNames()`
* `for...in`
* `in`
* Inheritance and the prototype chain


Object.entries() - JavaScript

Object.entries()
================

The **`Object.entries()`** static method returns an array of a given object's own enumerable string-keyed property key-value pairs.

Try it
------

Syntax
------

```js
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.

Description
-----------

`Object.entries()` returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.entries()` is the same as that provided by a `for...in` loop.

If you only need the property keys, use `Object.keys()` instead. If you only need the property values, use `Object.values()` instead.

Examples
--------

### Using Object.entries()

```js
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'] ]
```

### Using Object.entries() on primitives

Non-object arguments are coerced to objects. `undefined` and `null` cannot be coerced to objects and throw a `TypeError` upfront. Only strings may have own enumerable properties, while all other primitives return an empty array.

```js
// Strings have indices as enumerable own properties
console.log(Object.entries("foo")); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ]

// Other primitives except undefined and null have no own properties
console.log(Object.entries(100)); // []
```

### Converting an Object to a Map

The `Map()` constructor accepts an iterable of `entries`. With `Object.entries`, you can easily convert from `Object` to `Map`:

```js
const obj = { foo: "bar", baz: 42 };
const map = new Map(Object.entries(obj));
console.log(map); // Map(2) {"foo" => "bar", "baz" => 42}
```

### Iterating through an Object

Using array destructuring, you can iterate through objects easily.

```js
// Using for...of loop
const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
}

// Using array methods
Object.entries(obj).forEach(([key, value]) => {
  console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
});
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.entries |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Object.entries` in `core-js`
* Enumerability and ownership of properties
* `Object.keys()`
* `Object.values()`
* `Object.prototype.propertyIsEnumerable()`
* `Object.create()`
* `Object.fromEntries()`
* `Object.getOwnPropertyNames()`
* `Map.prototype.entries()`


Object.defineProperty() - JavaScript

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.

Try it
------

Syntax
------

```js
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.

### Return value

The object that was passed to the function, with the specified property added or modified.

Description
-----------

`Object.defineProperty()` allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (`for...in`, `Object.keys()`, etc.), whose values may be changed and which may be deleted. This method allows these extra details to be changed from their defaults. By default, properties added using `Object.defineProperty()` are not writable, not enumerable, and not configurable. In addition, `Object.defineProperty()` uses the `[[DefineOwnProperty]]` internal method, instead of `[[Set]]`, so it does not invoke setters, even when the property is already present.

Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A **data descriptor** is a property with a value that may or may not be writable. An **accessor descriptor** is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.

Both data and accessor descriptors are objects. They share the following optional keys (please note: the **defaults** mentioned here are in the case of defining properties using `Object.defineProperty()`):

`configurable`

when this is set to `false`,

* the type of this property cannot be changed between data property and accessor property, and
* the property may not be deleted, and
* other attributes of its descriptor cannot be changed (however, if it's a data descriptor with `writable: true`, the `value` can be changed, and `writable` can be changed to `false`).

**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 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. When the property is accessed, this function is called without arguments and with `this` set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The 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. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with `this` set to the object through which the property is assigned. **Defaults to `undefined`.**

If a descriptor doesn't have any of the `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.

These attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or create a `null`-prototype object.

```js
const obj = {};
// 1. Using a null prototype: no inherited properties
const descriptor = Object.create(null);
descriptor.value = "static";

// not enumerable, not configurable, not writable as defaults
Object.defineProperty(obj, "key", descriptor);

// 2. Being explicit by using a throw-away object literal with all attributes present
Object.defineProperty(obj, "key2", {
  enumerable: false,
  configurable: false,
  writable: false,
  value: "static",
});

// 3. Recycling same object
function withValue(value) {
  const d =
    withValue.d ||
    (withValue.d = {
      enumerable: false,
      writable: false,
      configurable: false,
      value,
    });

  // avoiding duplicate operation for assigning value
  if (d.value !== value) d.value = value;

  return d;
}
// and
Object.defineProperty(obj, "key", withValue("static"));

// if freeze is available, prevents adding or
// removing the object prototype properties
// (value, get, set, enumerable, writable, configurable)
(Object.freeze || Object)(Object.prototype);
```

When the property already exists, `Object.defineProperty()` attempts to modify the property according to the values in the descriptor and the property's current configuration.

If the old descriptor had its `configurable` attribute set to `false`, the property is said to be *non-configurable*. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with `writable: true`, it is possible to modify the value and change the `writable` attribute from `true` to `false`. A `TypeError` is thrown when attempts are made to change non-configurable property attributes (except `value` and `writable`, if permitted), except when defining a value same as the original value on a data property.

When the current property is configurable, defining an attribute to `undefined` effectively deletes it. For example, if `o.k` is an accessor property, `Object.defineProperty(o, "k", { set: undefined })` will remove the setter, making `k` only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to `undefined`). It is possible to toggle between data and accessor property by giving a descriptor of a different "flavor". For example, if the new descriptor is a data descriptor (with `value` or `writable`), the original descriptor's `get` and `set` attributes will both be dropped.

Examples
--------

### Creating a property

When the property specified doesn't exist in the object, `Object.defineProperty()` creates a new property as described. Fields may be omitted from the descriptor and default values for those fields are inputted.

```js
const o = {}; // Creates a new object

// Example of an object property added
// with defineProperty with a data property descriptor
Object.defineProperty(o, "a", {
  value: 37,
  writable: true,
  enumerable: true,
  configurable: true,
});
// 'a' property exists in the o object and its value is 37

// Example of an object property added
// with defineProperty with an accessor property descriptor
let bValue = 38;
Object.defineProperty(o, "b", {
  get() {
    return bValue;
  },
  set(newValue) {
    bValue = newValue;
  },
  enumerable: true,
  configurable: true,
});
o.b; // 38
// 'b' property exists in the o object and its value is 38
// The value of o.b is now always identical to bValue,
// unless o.b is redefined

// You cannot try to mix both:
Object.defineProperty(o, "conflict", {
  value: 0x9f91102,
  get() {
    return 0xdeadbeef;
  },
});
// throws a TypeError: value appears
// only in data descriptors,
// get appears only in accessor descriptors
```

### Modifying a property

When modifying an existing property, the current property configuration determines if the operator succeeds, does nothing, or throws a `TypeError`.

#### Writable attribute

When the `writable` property attribute is `false`, the property is said to be "non-writable". It cannot be reassigned. Trying to write to a non-writable property doesn't change it and results in an error in strict mode.

```js
const o = {}; // Creates a new object

Object.defineProperty(o, "a", {
  value: 37,
  writable: false,
});

console.log(o.a); // 37
o.a = 25; // No error thrown
// (it would throw in strict mode,
// even if the value had been the same)
console.log(o.a); // 37; the assignment didn't work

// strict mode
(() => {
  "use strict";
  const o = {};
  Object.defineProperty(o, "b", {
    value: 2,
    writable: false,
  });
  o.b = 3; // throws TypeError: "b" is read-only
  return o.b; // returns 2 without the line above
})();
```

#### Enumerable attribute

The `enumerable` property attribute defines whether the property is considered by `Object.assign()` or the spread operator. For non-`Symbol` properties, it also defines whether it shows up in a `for...in` loop and `Object.keys()` or not. For more information, see Enumerability and ownership of properties.

```js
const o = {};
Object.defineProperty(o, "a", {
  value: 1,
  enumerable: true,
});
Object.defineProperty(o, "b", {
  value: 2,
  enumerable: false,
});
Object.defineProperty(o, "c", {
  value: 3,
}); // enumerable defaults to false
o.d = 4; // enumerable defaults to true when creating a property by setting it
Object.defineProperty(o, Symbol.for("e"), {
  value: 5,
  enumerable: true,
});
Object.defineProperty(o, Symbol.for("f"), {
  value: 6,
  enumerable: false,
});

for (const i in o) {
  console.log(i);
}
// Logs 'a' and 'd' (always in that order)

Object.keys(o); // ['a', 'd']

o.propertyIsEnumerable("a"); // true
o.propertyIsEnumerable("b"); // false
o.propertyIsEnumerable("c"); // false
o.propertyIsEnumerable("d"); // true
o.propertyIsEnumerable(Symbol.for("e")); // true
o.propertyIsEnumerable(Symbol.for("f")); // false

const p = { ...o };
p.a; // 1
p.b; // undefined
p.c; // undefined
p.d; // 4
p[Symbol.for("e")]; // 5
p[Symbol.for("f")]; // undefined
```

#### Configurable attribute

The `configurable` attribute controls whether the property can be deleted from the object and whether its attributes (other than `value` and `writable`) can be changed.

This example illustrates a non-configurable accessor property.

```js
const o = {};
Object.defineProperty(o, "a", {
  get() {
    return 1;
  },
  configurable: false,
});

Object.defineProperty(o, "a", {
  configurable: true,
}); // throws a TypeError
Object.defineProperty(o, "a", {
  enumerable: true,
}); // throws a TypeError
Object.defineProperty(o, "a", {
  set() {},
}); // throws a TypeError (set was undefined previously)
Object.defineProperty(o, "a", {
  get() {
    return 1;
  },
}); // throws a TypeError
// (even though the new get does exactly the same thing)
Object.defineProperty(o, "a", {
  value: 12,
}); // throws a TypeError
// ('value' can be changed when 'configurable' is false, but only when the property is a writable data property)

console.log(o.a); // 1
delete o.a; // Nothing happens; throws an error in strict mode
console.log(o.a); // 1
```

If the `configurable` attribute of `o.a` had been `true`, none of the errors would be thrown and the property would be deleted at the end.

This example illustrates a non-configurable but writable data property. The property's `value` can still be changed, and `writable` can still be toggled from `true` to `false`.

```js
const o = {};
Object.defineProperty(o, "b", {
  writable: true,
  configurable: false,
});
console.log(o.b); // undefined
Object.defineProperty(o, "b", {
  value: 1,
}); // Even when configurable is false, because the object is writable, we may still replace the value
console.log(o.b); // 1
o.b = 2; // We can change the value with assignment operators as well
console.log(o.b); // 2
// Toggle the property's writability
Object.defineProperty(o, "b", {
  writable: false,
});
Object.defineProperty(o, "b", {
  value: 1,
}); // TypeError: because the property is neither writable nor configurable, it cannot be modified
// At this point, there's no way to further modify 'b'
// or restore its writability
```

This example illustrates a configurable but non-writable data property. The property's `value` may still be replaced with `defineProperty` (but not with assignment operators), and `writable` may be toggled.

```js
const o = {};
Object.defineProperty(o, "b", {
  writable: false,
  configurable: true,
});
Object.defineProperty(o, "b", {
  value: 1,
}); // We can replace the value with defineProperty
console.log(o.b); // 1
o.b = 2; // throws TypeError in strict mode: cannot change a non-writable property's value with assignment
```

This example illustrates a non-configurable and non-writable data property. There's no way to update any attribute of the property, including its `value`.

```js
const o = {};
Object.defineProperty(o, "b", {
  writable: false,
  configurable: false,
});
Object.defineProperty(o, "b", {
  value: 1,
}); // TypeError: the property cannot be modified because it is neither writable nor configurable.
```

### Adding properties and default values

It is important to consider the way default values of attributes are applied. There is often a difference between using property accessors to assign a value and using `Object.defineProperty()`, as shown in the example below.

```js
const o = {};

o.a = 1;
// is equivalent to:
Object.defineProperty(o, "a", {
  value: 1,
  writable: true,
  configurable: true,
  enumerable: true,
});

// On the other hand,
Object.defineProperty(o, "a", { value: 1 });
// is equivalent to:
Object.defineProperty(o, "a", {
  value: 1,
  writable: false,
  configurable: false,
  enumerable: false,
});
```

### Custom setters and getters

The example below shows how to implement a self-archiving object. When `temperature` property is set, the `archive` array gets a log entry.

```js
function Archiver() {
  let temperature = null;
  const archive = [];

  Object.defineProperty(this, "temperature", {
    get() {
      console.log("get!");
      return temperature;
    },
    set(value) {
      temperature = value;
      archive.push({ val: temperature });
    },
  });

  this.getArchive = () => archive;
}

const arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
arc.getArchive(); // [{ val: 11 }, { val: 13 }]
```

In this example, a getter always returns the same value.

```js
const pattern = {
  get() {
    return "I always return this string, whatever you have assigned";
  },
  set() {
    this.myname = "this is my name string";
  },
};

function TestDefineSetAndGet() {
  Object.defineProperty(this, "myproperty", pattern);
}

const instance = new TestDefineSetAndGet();
instance.myproperty = "test";
console.log(instance.myproperty);
// I always return this string, whatever you have assigned

console.log(instance.myname); // this is my name string
```

### Inheritance of properties

If an accessor property is inherited, its `get` and `set` methods will be called when the property is accessed and modified on descendant objects. If these methods use a variable to store the value, this value will be shared by all objects.

```js
function MyClass() {}

let value;
Object.defineProperty(MyClass.prototype, "x", {
  get() {
    return value;
  },
  set(x) {
    value = x;
  },
});

const a = new MyClass();
const b = new MyClass();
a.x = 1;
console.log(b.x); // 1
```

This can be fixed by storing the value in another property. In `get` and `set` methods, `this` points to the object which is used to access or modify the property.

```js
function MyClass() {}

Object.defineProperty(MyClass.prototype, "x", {
  get() {
    return this.storedX;
  },
  set(x) {
    this.storedX = x;
  },
});

const a = new MyClass();
const b = new MyClass();
a.x = 1;
console.log(b.x); // undefined
```

Unlike accessor properties, data properties are always set on the object itself, not on a prototype. However, if a non-writable data property is inherited, it is still prevented from being modified on the object.

```js
function MyClass() {}

MyClass.prototype.x = 1;
Object.defineProperty(MyClass.prototype, "y", {
  writable: false,
  value: 1,
});

const a = new MyClass();
a.x = 2;
console.log(a.x); // 2
console.log(MyClass.prototype.x); // 1
a.y = 2; // Ignored, throws in strict mode
console.log(a.y); // 1
console.log(MyClass.prototype.y); // 1
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.defineproperty |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Enumerability and ownership of properties
* `Object.defineProperties()`
* `Object.prototype.propertyIsEnumerable()`
* `Object.getOwnPropertyDescriptor()`
* `get`
* `set`
* `Object.create()`
* `Reflect.defineProperty()`


Object.preventExtensions() - JavaScript

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.

Try it
------

Syntax
------

```js
Object.preventExtensions(obj)
```

### Parameters

`obj`

The object which should be made non-extensible.

### Return value

The object being made non-extensible.

Description
-----------

 An object is extensible if new properties can be added to it.
 `Object.preventExtensions()` marks an object as no longer extensible, so that
 it will never have properties beyond the ones it had at the time it was marked as
 non-extensible. Note that the properties of a non-extensible object, in general, may
 still be *deleted*. Attempting to add new properties to a non-extensible object
 will fail, either silently or, in strict mode, throwing a `TypeError`.

Unlike `Object.seal()` and `Object.freeze()`, `Object.preventExtensions()` invokes an intrinsic JavaScript behavior and cannot be replaced with a composition of several other operations. It also has its `Reflect` counterpart (which only exists for intrinsic operations), `Reflect.preventExtensions()`.

`Object.preventExtensions()` only prevents addition of own properties. Properties can still be added to the object prototype.

This method makes the `[[Prototype]]` of the target immutable; any `[[Prototype]]` re-assignment will throw a `TypeError`. This behavior is specific to the internal `[[Prototype]]` property; other properties of the target object will remain mutable.

There is no way to make an object extensible again once it has been made non-extensible.

Examples
--------

### Using Object.preventExtensions

```js
// 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();
```

A non-extensible object's prototype is immutable:

```js
const fixed = Object.preventExtensions({});
// throws a 'TypeError'.
fixed.__proto__ = { oh: "hai" };
```

### Non-object argument

In ES5, if the argument to this method is not an object (a primitive), then it will cause a `TypeError`. In ES2015, a non-object argument will be returned as-is without any errors, since primitives are already, by definition, immutable.

```js
Object.preventExtensions(1);
// TypeError: 1 is not an object (ES5 code)

Object.preventExtensions(1);
// 1 (ES2015 code)
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.preventextensions |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Object.isExtensible()`
* `Object.seal()`
* `Object.isSealed()`
* `Object.freeze()`
* `Object.isFrozen()`
* `Reflect.preventExtensions()`


Object.assign() - JavaScript

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.

Try it
------

Syntax
------

```js
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.

Description
-----------

 Properties in the target object are overwritten by properties in the sources if they
 have the same key. Later sources' properties
 overwrite earlier ones.

 The `Object.assign()` method only copies *enumerable* and
 *own* properties from a source object to a target object. It uses
 `[[Get]]` on the source and `[[Set]]` on the target, so it will
 invoke getters and setters. Therefore it
 *assigns* properties, versus copying or defining new properties. This may make it
 unsuitable for merging new properties into a prototype if the merge sources contain
 getters.

 For copying property definitions (including their enumerability) into prototypes, use
 `Object.getOwnPropertyDescriptor()` and
 `Object.defineProperty()` instead.

Both `String` and `Symbol` properties are copied.

 In case of an error, for example if a property is non-writable, a
 `TypeError` is raised, and the `target` object is
 changed if any properties are added before the error is raised.

**Note:** `Object.assign()` does not throw on
 `null` or `undefined` sources.

Examples
--------

### Cloning an object

```js
const obj = { a: 1 };
const copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
```

### Warning for Deep Clone

 For deep cloning, we need to use alternatives like `structuredClone()`, because `Object.assign()`
 copies property values.

If the source value is a reference to an object, it only copies the reference value.

```js
const obj1 = { a: 0, b: { c: 0 } };
const obj2 = Object.assign({}, obj1);
console.log(obj2); // { a: 0, b: { c: 0 } }

obj1.a = 1;
console.log(obj1); // { a: 1, b: { c: 0 } }
console.log(obj2); // { a: 0, b: { c: 0 } }

obj2.a = 2;
console.log(obj1); // { a: 1, b: { c: 0 } }
console.log(obj2); // { a: 2, b: { c: 0 } }

obj2.b.c = 3;
console.log(obj1); // { a: 1, b: { c: 3 } }
console.log(obj2); // { a: 2, b: { c: 3 } }

// Deep Clone
const obj3 = { a: 0, b: { c: 0 } };
const obj4 = structuredClone(obj3);
obj3.a = 4;
obj3.b.c = 4;
console.log(obj4); // { a: 0, b: { c: 0 } }
```

### Merging objects

```js
const o1 = { a: 1 };
const o2 = { b: 2 };
const o3 = { c: 3 };

const obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
```

### Merging objects with same properties

```js
const o1 = { a: 1, b: 1, c: 1 };
const o2 = { b: 2, c: 2 };
const o3 = { c: 3 };

const obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
```

 The properties are overwritten by other objects that have the same properties later in
 the parameters order.

### Copying symbol-typed properties

```js
const o1 = { a: 1 };
const o2 = { [Symbol("foo")]: 2 };

const obj = Object.assign({}, o1, o2);
console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox)
Object.getOwnPropertySymbols(obj); // [Symbol(foo)]
```

### Properties on the prototype chain and non-enumerable properties cannot be copied

```js
const obj = Object.create(
  // foo is on obj's prototype chain.
  { foo: 1 },
  {
    bar: {
      value: 2, // bar is a non-enumerable property.
    },
    baz: {
      value: 3,
      enumerable: true, // baz is an own enumerable property.
    },
  },
);

const copy = Object.assign({}, obj);
console.log(copy); // { baz: 3 }
```

### Primitives will be wrapped to objects

```js
const v1 = "abc";
const v2 = true;
const v3 = 10;
const v4 = Symbol("foo");

const obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
// Primitives will be wrapped, null and undefined will be ignored.
// Note, only string wrappers can have own enumerable properties.
console.log(obj); // { "0": "a", "1": "b", "2": "c" }
```

### Exceptions will interrupt the ongoing copying task

```js
const target = Object.defineProperty({}, "foo", {
  value: 1,
  writable: false,
}); // target.foo is a read-only property

Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
// TypeError: "foo" is read-only
// The Exception is thrown when assigning target.foo

console.log(target.bar); // 2, the first source was copied successfully.
console.log(target.foo2); // 3, the first property of the second source was copied successfully.
console.log(target.foo); // 1, exception is thrown here.
console.log(target.foo3); // undefined, assign method has finished, foo3 will not be copied.
console.log(target.baz); // undefined, the third source will not be copied either.
```

### Copying accessors

```js
const obj = {
  foo: 1,
  get bar() {
    return 2;
  },
};

let copy = Object.assign({}, obj);
console.log(copy);
// { foo: 1, bar: 2 }
// The value of copy.bar is obj.bar's getter's return value.

// This is an assign function that copies full descriptors
function completeAssign(target, ...sources) {
  sources.forEach((source) => {
    const descriptors = Object.keys(source).reduce((descriptors, key) => {
      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
      return descriptors;
    }, {});

    // By default, Object.assign copies enumerable Symbols, too
    Object.getOwnPropertySymbols(source).forEach((sym) => {
      const descriptor = Object.getOwnPropertyDescriptor(source, sym);
      if (descriptor.enumerable) {
        descriptors[sym] = descriptor;
      }
    });
    Object.defineProperties(target, descriptors);
  });
  return target;
}

copy = completeAssign({}, obj);
console.log(copy);
// { foo:1, get bar() { return 2 } }
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.assign |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Object.assign` in `core-js`
* `Object.defineProperties()`
* Enumerability and ownership of properties
* Spread in object literals


Object.prototype.__proto__ - JavaScript

Object.prototype.\_\_proto\_\_
==============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `obj.__proto__ = ...` statement, but may extend to ***any*** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in JavaScript engine fundamentals: optimizing prototypes.

**Note:** The use of `__proto__` is controversial and discouraged. Its existence and exact behavior have only been standardized as a legacy feature to ensure web compatibility, while it presents several security issues and footguns. For better support, prefer `Object.getPrototypeOf()`/`Reflect.getPrototypeOf()` and `Object.setPrototypeOf()`/`Reflect.setPrototypeOf()` instead.

The **`__proto__`** accessor property of `Object` instances exposes the `[[Prototype]]` (either an object or `null`) of this object.

The `__proto__` property can also be used in an object literal definition to set the object `[[Prototype]]` on creation, as an alternative to `Object.create()`. See: object initializer / literal syntax. That syntax is standard and optimized for in implementations, and quite different from `Object.prototype.__proto__`.

Syntax
------

```js
obj.__proto__
```

### Return value

If used as a getter, returns the object's `[[Prototype]]`.

### Exceptions

`TypeError`

Thrown if attempting to set the prototype of a non-extensible object or an immutable prototype exotic object, such as `Object.prototype` or `window`.

Description
-----------

The `__proto__` getter function exposes the value of the internal `[[Prototype]]` of an object. For objects created using an object literal (unless you use the prototype setter syntax), this value is `Object.prototype`. For objects created using array literals, this value is `Array.prototype`. For functions, this value is `Function.prototype`. You can read more about the prototype chain in Inheritance and the prototype chain.

The `__proto__` setter allows the `[[Prototype]]` of an object to be mutated. The value provided must be an object or `null`. Providing any other value will do nothing.

Unlike `Object.getPrototypeOf()` and `Object.setPrototypeOf()`, which are always available on `Object` as static properties and always reflect the `[[Prototype]]` internal property, the `__proto__` property doesn't always exist as a property on all objects, and as a result doesn't reflect `[[Prototype]]` reliably.

The `__proto__` property is a simple accessor property on `Object.prototype` consisting of a getter and setter function. A property access for `__proto__` that eventually consults `Object.prototype` will find this property, but an access that does not consult `Object.prototype` will not. If some other `__proto__` property is found before `Object.prototype` is consulted, that property will hide the one found on `Object.prototype`.

`null`-prototype objects don't inherit any property from `Object.prototype`, including the `__proto__` accessor property, so if you try to read `__proto__` on such an object, the value is always `undefined` regardless of the object's actual `[[Prototype]]`, and any assignment to `__proto__` would create a new property called `__proto__` instead of setting the object's prototype. Furthermore, `__proto__` can be redefined as an own property on any object instance through `Object.defineProperty()` without triggering the setter. In this case, `__proto__` will no longer be an accessor for `[[Prototype]]`. Therefore, always prefer `Object.getPrototypeOf()` and `Object.setPrototypeOf()` for setting and getting the `[[Prototype]]` of an object.

Examples
--------

### Using \_\_proto\_\_

```js
function Circle() {}
const shape = {};
const circle = new Circle();

// Set the object prototype.
// DEPRECATED. This is for example purposes only. DO NOT DO THIS in real code.
shape.__proto__ = circle;

// Get the object prototype
console.log(shape.__proto__ === Circle); // false
```

```js
const ShapeA = function () {};
const ShapeB = {
  a() {
    console.log("aaa");
  },
};

ShapeA.prototype.__proto__ = ShapeB;
console.log(ShapeA.prototype.__proto__); // { a: [Function: a] }

const shapeA = new ShapeA();
shapeA.a(); // aaa
console.log(ShapeA.prototype === shapeA.__proto__); // true
```

```js
const ShapeC = function () {};
const ShapeD = {
  a() {
    console.log("a");
  },
};

const shapeC = new ShapeC();
shapeC.__proto__ = ShapeD;
shapeC.a(); // a
console.log(ShapeC.prototype === shapeC.__proto__); // false
```

```js
function Test() {}
Test.prototype.myName = function () {
  console.log("myName");
};

const test = new Test();
console.log(test.__proto__ === Test.prototype); // true
test.myName(); // myName

const obj = {};
obj.__proto__ = Test.prototype;
obj.myName(); // myName
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.prototype.\_\_proto\_\_ |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Object.prototype.isPrototypeOf()`
* `Object.getPrototypeOf()`
* `Object.setPrototypeOf()`


Object.prototype.__defineGetter__() - JavaScript

Object.prototype.\_\_defineGetter\_\_()
=======================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Note:** This feature is deprecated in favor of defining getters using the object initializer syntax or the `Object.defineProperty()` API. This method's behavior is only specified for web compatibility, and is not required to be implemented in any platform. It may not work everywhere.

The **`__defineGetter__()`** method of `Object` instances binds an object's property to a function to be called when that property is looked up.

Syntax
------

```js
\_\_defineGetter\_\_(prop, func)
```

### Parameters

`prop`

A string containing the name of the property that the getter `func` is bound to.

`func`

A function to be bound to a lookup of the specified property.

### Return value

None (`undefined`).

### Exceptions

`TypeError`

Thrown if `func` is not a function.

Description
-----------

All objects that inherit from `Object.prototype` (that is, all except `null`-prototype objects) inherit the `__defineGetter__()` method. This method allows a getter to be defined on a pre-existing object. This is equivalent to `Object.defineProperty(obj, prop, { get: func, configurable: true, enumerable: true })`, which means the property is enumerable and configurable, and any existing setter, if present, is preserved.

`__defineGetter__()` is defined in the spec as "normative optional", which means no implementation is required to implement this. However, all major browsers implement it, and due to its continued usage, it's unlikely to be removed. If a browser implements `__defineGetter__()`, it also needs to implement the `__lookupGetter__()`, `__lookupSetter__()`, and `__defineSetter__()` methods.

Examples
--------

### Using \_\_defineGetter\_\_()

```js
const o = {};
o.\_\_defineGetter\_\_("gimmeFive", function () {
  return 5;
});
console.log(o.gimmeFive); // 5
```

### Defining a getter property in standard ways

You can use the `get` syntax to define a getter when the object is first initialized.

```js
const o = {
  get gimmeFive() {
    return 5;
  },
};
console.log(o.gimmeFive); // 5
```

You may also use `Object.defineProperty()` to define a getter on an object after it's been created. Compared to `__defineGetter__()`, this method allows you to control the getter's enumerability and configurability, as well as defining symbol properties. The `Object.defineProperty()` method also works with `null`-prototype objects, which don't inherit from `Object.prototype` and therefore don't have the `__defineGetter__()` method.

```js
const o = {};
Object.defineProperty(o, "gimmeFive", {
  get() {
    return 5;
  },
  configurable: true,
  enumerable: true,
});
console.log(o.gimmeFive); // 5
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.prototype.\_\_defineGetter\_\_ |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Object.prototype.__defineGetter__` in `core-js`
* `Object.prototype.__defineSetter__()`
* `get`
* `Object.defineProperty()`
* `Object.prototype.__lookupGetter__()`
* `Object.prototype.__lookupSetter__()`
* JS Guide: Defining Getters and Setters
* Firefox bug 647423