Set - JavaScript

Set
===

The **`Set`** object lets you store unique values of any type, whether primitive values or object references.

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

`Set` objects are collections of values. A value in the set **may only occur once**; it is unique in the set's collection. You can iterate through the elements of a set in insertion order. The *insertion order* corresponds to the order in which each element was inserted into the set by the `add()` method successfully (that is, there wasn't an identical element already in the set when `add()` was called).

The specification requires sets to be implemented "that, on average, provide access times that are sublinear on the number of elements in the collection". Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N).

### Value equality

Value equality is based on the SameValueZero algorithm. (It used to use SameValue, which treated `0` and `-0` as different. Check browser compatibility.) This means `NaN` is considered the same as `NaN` (even though `NaN !== NaN`) and all other values are considered equal according to the semantics of the `===` operator.

### Performance

The `has` method checks if a value is in the set, using an approach that is, on average, quicker than testing most of the elements that have previously been added to the set. In particular, it is, on average, faster than the `Array.prototype.includes` method when an array has a `length` equal to a set's `size`.

### Set composition

The `Set` object provides some methods that allow you to compose sets like you would with mathematical operations. These methods include:

| Method | Return type | Mathematical equivalent | Venn diagram |
| --- | --- | --- | --- |
| `A.difference(B)` | `Set` |

A
∖
B

A\setminus B

 | A Venn diagram where two circles overlap. The difference of A and B is the part of A that is not overlapping B. |
| `A.intersection(B)` | `Set` |

A
∩
B

A\cap B

 | A Venn diagram where two circles overlap. The intersection of A and B is the part where they overlap. |
| `A.symmetricDifference(B)` | `Set` |

(
A
∖
B
)
∪
(
B
∖
A
)

(A\setminus B)\cup(B\setminus A)

 | A Venn diagram where two circles overlap. The symmetric difference of A and B is the region contained by either circle but not both. |
| `A.union(B)` | `Set` |

A
∪
B

A\cup B

 | A Venn diagram where two circles overlap. The symmetric difference of A and B is the region contained by either or both circles. |
| `A.isDisjointFrom(B)` | `Boolean` |

A
∩
B
=
∅

A\cap B = \empty

 | A Venn diagram with two circles. A and B are disjoint because the circles have no region of overlap. |
| `A.isSubsetOf(B)` | `Boolean` |

A
⊆
B

A\subseteq B

 | A Venn diragram with two circles. A is a subset of B because A is completely contained in B. |
| `A.isSupersetOf(B)` | `Boolean` |

A
⊇
B

A\supseteq B

 | A Venn diagram with two circles. A is a superset of B because B is completely contained in A. |

To make them more generalizable, these methods don't just accept `Set` objects, but anything that's set-like.

### Set-like objects

All set composition methods require `this` to be an actual `Set` instance, but their arguments just need to be set-like. A *set-like object* is an object that provides the following:

* A `size` property that contains a number.
* A `has()` method that takes an element and returns a boolean.
* A `keys()` method that returns an iterator of the elements in the set.

For example, `Map` objects are set-like because they also have `size`, `has()`, and `keys()`, so they behave just like sets of keys when used in set methods:

```js
const a = new Set([1, 2, 3]);
const b = new Map([
  [1, "one"],
  [2, "two"],
  [4, "four"],
]);
console.log(a.union(b)); // Set(4) {1, 2, 3, 4}
```

**Note:** The set-like protocol invokes the `keys()` method instead of `[@@iterator]()` to produce elements. This is to make maps valid set-like objects, because for maps, the iterator produces *entries* but the `has()` method takes *keys*.

Arrays are not set-like because they don't have a `has()` method or the `size` property, and their `keys()` method produces indices instead of elements. `WeakSet` objects are also not set-like because they don't have a `keys()` method.

### Set-like browser APIs

Browser **`Set`-like objects** (or "setlike objects") are Web API interfaces that behave in many ways like a `Set`.

 Just like `Set`, elements can be iterated in the same order that they were added to the object.
 `Set`-like objects and `Set` also have properties and methods that share the same name and behavior.
 However unlike `Set` they only allow a specific predefined type for each entry.

 The allowed types are set in the specification IDL definition.
 For example, `GPUSupportedFeatures` is a `Set`-like object that must use strings as the key/value.
 This is defined in the specification IDL below:

```webidl
interface GPUSupportedFeatures {
  readonly setlike<DOMString>;
};
```

`Set`-like objects are either read-only or read-writable (see the `readonly` keyword in the IDL above).

* Read-only `Set`-like objects have the property `size`, and the methods: `entries()`, `forEach()`, `has()`, `keys()`, `values()`, and `@@iterator`.
* Writeable `Set`-like objects additionally have the methods: `clear()`, `delete()`, and `add()`.

The methods and properties have the same behavior as the equivalent entities in `Set`, except for the restriction on the types of the entry.

The following are examples of read-only `Set`-like browser objects:

* `GPUSupportedFeatures`
* `XRAnchorSet`

The following are examples of writable `Set`-like browser objects:

* `CustomStateSet`
* `FontFaceSet`
* `Highlight`
Constructor
-----------

`Set()`

Creates a new `Set` object.

Static properties
-----------------

`Set[@@species]`

The constructor function that is used to create derived objects.

Instance properties
-------------------

These properties are defined on `Set.prototype` and shared by all `Set` instances.

`Set.prototype.constructor`

The constructor function that created the instance object. For `Set` instances, the initial value is the `Set` constructor.

`Set.prototype.size`

Returns the number of values in the `Set` object.

`Set.prototype[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"Set"`. This property is used in `Object.prototype.toString()`.

Instance methods
----------------

`Set.prototype.add()`

Inserts a new element with a specified value in to a `Set` object, if there isn't an element with the same value already in the `Set`.

`Set.prototype.clear()`

Removes all elements from the `Set` object.

`Set.prototype.delete()`

Removes the element associated to the `value` and returns a boolean asserting whether an element was successfully removed or not. `Set.prototype.has(value)` will return `false` afterwards.

`Set.prototype.difference()`
Experimental

Takes a set and returns a new set containing elements in this set but not in the given set.

`Set.prototype.entries()`

Returns a new iterator object that contains **an array of `[value, value]`** for each element in the `Set` object, in insertion order. This is similar to the `Map` object, so that each entry's *key* is the same as its *value* for a `Set`.

`Set.prototype.forEach()`

Calls `callbackFn` once for each value present in the `Set` object, in insertion order. If a `thisArg` parameter is provided, it will be used as the `this` value for each invocation of `callbackFn`.

`Set.prototype.has()`

Returns a boolean asserting whether an element is present with the given value in the `Set` object or not.

`Set.prototype.intersection()`
Experimental

Takes a set and returns a new set containing elements in both this set and the given set.

`Set.prototype.isDisjointFrom()`
Experimental

Takes a set and returns a boolean indicating if this set has no elements in common with the given set.

`Set.prototype.isSubsetOf()`
Experimental

Takes a set and returns a boolean indicating if all elements of this set are in the given set.

`Set.prototype.isSupersetOf()`
Experimental

Takes a set and returns a boolean indicating if all elements of the given set are in this set.

`Set.prototype.keys()`

An alias for `Set.prototype.values()`.

`Set.prototype.symmetricDifference()`
Experimental

Takes a set and returns a new set containing elements which are in either this set or the given set, but not in both.

`Set.prototype.union()`
Experimental

Takes a set and returns a new set containing elements which are in either or both of this set and the given set.

`Set.prototype.values()`

Returns a new iterator object that yields the **values** for each element in the `Set` object in insertion order.

`Set.prototype[@@iterator]()`

Returns a new iterator object that yields the **values** for each element in the `Set` object in insertion order.

Examples
--------

### Using the Set object

```js
const mySet1 = new Set();

mySet1.add(1); // Set(1) { 1 }
mySet1.add(5); // Set(2) { 1, 5 }
mySet1.add(5); // Set(2) { 1, 5 }
mySet1.add("some text"); // Set(3) { 1, 5, 'some text' }
const o = { a: 1, b: 2 };
mySet1.add(o);

mySet1.add({ a: 1, b: 2 }); // o is referencing a different object, so this is okay

mySet1.has(1); // true
mySet1.has(3); // false, since 3 has not been added to the set
mySet1.has(5); // true
mySet1.has(Math.sqrt(25)); // true
mySet1.has("Some Text".toLowerCase()); // true
mySet1.has(o); // true

mySet1.size; // 5

mySet1.delete(5); // removes 5 from the set
mySet1.has(5); // false, 5 has been removed

mySet1.size; // 4, since we just removed one value

mySet1.add(5); // Set(5) { 1, 'some text', {...}, {...}, 5 } - a previously deleted item will be added as a new item, it will not retain its original position before deletion

console.log(mySet1); // Set(5) { 1, "some text", {…}, {…}, 5 }
```

### Iterating sets

The iteration over a set visits elements in insertion order.

```js
for (const item of mySet1) {
  console.log(item);
}
// 1, "some text", { "a": 1, "b": 2 }, { "a": 1, "b": 2 }, 5

for (const item of mySet1.keys()) {
  console.log(item);
}
// 1, "some text", { "a": 1, "b": 2 }, { "a": 1, "b": 2 }, 5

for (const item of mySet1.values()) {
  console.log(item);
}
// 1, "some text", { "a": 1, "b": 2 }, { "a": 1, "b": 2 }, 5

// key and value are the same here
for (const [key, value] of mySet1.entries()) {
  console.log(key);
}
// 1, "some text", { "a": 1, "b": 2 }, { "a": 1, "b": 2 }, 5

// Convert Set object to an Array object, with Array.from
const myArr = Array.from(mySet1); // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}, 5]

// the following will also work if run in an HTML document
mySet1.add(document.body);
mySet1.has(document.querySelector("body")); // true

// converting between Set and Array
const mySet2 = new Set([1, 2, 3, 4]);
console.log(mySet2.size); // 4
console.log([...mySet2]); // [1, 2, 3, 4]

// intersect can be simulated via
const intersection = new Set([...mySet1].filter((x) => mySet2.has(x)));

// difference can be simulated via
const difference = new Set([...mySet1].filter((x) => !mySet2.has(x)));

// Iterate set entries with forEach()
mySet2.forEach((value) => {
  console.log(value);
});
// 1
// 2
// 3
// 4
```

### Implementing basic set operations

```js
function isSuperset(set, subset) {
  for (const elem of subset) {
    if (!set.has(elem)) {
      return false;
    }
  }
  return true;
}

function union(setA, setB) {
  const _union = new Set(setA);
  for (const elem of setB) {
    _union.add(elem);
  }
  return _union;
}

function intersection(setA, setB) {
  const _intersection = new Set();
  for (const elem of setB) {
    if (setA.has(elem)) {
      _intersection.add(elem);
    }
  }
  return _intersection;
}

function symmetricDifference(setA, setB) {
  const _difference = new Set(setA);
  for (const elem of setB) {
    if (_difference.has(elem)) {
      _difference.delete(elem);
    } else {
      _difference.add(elem);
    }
  }
  return _difference;
}

function difference(setA, setB) {
  const _difference = new Set(setA);
  for (const elem of setB) {
    _difference.delete(elem);
  }
  return _difference;
}

// Examples
const setA = new Set([1, 2, 3, 4]);
const setB = new Set([2, 3]);
const setC = new Set([3, 4, 5, 6]);

isSuperset(setA, setB); // returns true
union(setA, setC); // returns Set {1, 2, 3, 4, 5, 6}
intersection(setA, setC); // returns Set {3, 4}
symmetricDifference(setA, setC); // returns Set {1, 2, 5, 6}
difference(setA, setC); // returns Set {1, 2}
```

### Relation to arrays

```js
const myArray = ["value1", "value2", "value3"];

// Use the regular Set constructor to transform an Array into a Set
const mySet = new Set(myArray);

mySet.has("value1"); // returns true

// Use the spread syntax to transform a set into an Array.
console.log([...mySet]); // Will show you exactly the same Array as myArray
```

### Remove duplicate elements from an array

```js
// Use to remove duplicate elements from an array
const numbers = [2, 13, 4, 4, 2, 13, 13, 4, 4, 5, 5, 6, 6, 7, 5, 32, 13, 4, 5];

console.log([...new Set(numbers)]); // [2, 13, 4, 5, 6, 7, 32]
```

### Relation to strings

```js
// Case sensitive (set will contain "F" and "f")
new Set("Firefox"); // Set(7) [ "F", "i", "r", "e", "f", "o", "x" ]

// Duplicate omission ("f" occurs twice in the string but set will contain only one)
new Set("firefox"); // Set(6) [ "f", "i", "r", "e", "o", "x" ]
```

### Use a set to ensure the uniqueness of a list of values

```js
const array = Array.from(document.querySelectorAll("[id]")).map((e) => e.id);

const set = new Set(array);
console.assert(set.size === array.length);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-set-objects |

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

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

See also
--------

* Polyfill of `Set` in `core-js`
* `Map`
* `WeakMap`
* `WeakSet`


Symbol - JavaScript

Symbol
======

**`Symbol`** is a built-in object whose constructor returns a `symbol` primitive — also called a **Symbol value** or just a **Symbol** — that's guaranteed to be unique. Symbols are often used to add unique property keys to an object that won't collide with keys any other code might add to the object, and which are hidden from any mechanisms other code will typically use to access the object. That enables a form of weak encapsulation, or a weak form of information hiding.

Every `Symbol()` call is guaranteed to return a unique Symbol. Every `Symbol.for("key")` call will always return the same Symbol for a given value of `"key"`. When `Symbol.for("key")` is called, if a Symbol with the given key can be found in the global Symbol registry, that Symbol is returned. Otherwise, a new Symbol is created, added to the global Symbol registry under the given key, and returned.

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

To create a new primitive Symbol, you write `Symbol()` with an optional string as its description:

```js
const sym1 = Symbol();
const sym2 = Symbol("foo");
const sym3 = Symbol("foo");
```

The above code creates three new Symbols. Note that `Symbol("foo")` does not coerce the string `"foo"` into a Symbol. It creates a new Symbol each time:

```js
Symbol("foo") === Symbol("foo"); // false
```

The following syntax with the `new` operator will throw a `TypeError`:

```js
const sym = new Symbol(); // TypeError
```

This prevents authors from creating an explicit `Symbol` wrapper object instead of a new Symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, `new Boolean`, `new String` and `new Number`).

If you really want to create a `Symbol` wrapper object, you can use the `Object()` function:

```js
const sym = Symbol("foo");
typeof sym; // "symbol"
const symObj = Object(sym);
typeof symObj; // "object"
```

Because symbols are the only primitive data type that has reference identity (that is, you cannot create the same symbol twice), they behave like objects in some way. For example, they are garbage collectable and can therefore be stored in `WeakMap`, `WeakSet`, `WeakRef`, and `FinalizationRegistry` objects.

### Shared Symbols in the global Symbol registry

The above syntax using the `Symbol()` function will create a Symbol whose value remains unique throughout the lifetime of the program. To create Symbols available across files and even across realms (each of which has its own global scope), use the methods `Symbol.for()` and `Symbol.keyFor()` to set and retrieve Symbols from the global Symbol registry.

Note that the "global Symbol registry" is only a fictitious concept and may not correspond to any internal data structure in the JavaScript engine — and even if such a registry exists, its content is not available to the JavaScript code, except through the `for()` and `keyFor()` methods.

The method `Symbol.for(tokenString)` takes a string key and returns a symbol value from the registry, while `Symbol.keyFor(symbolValue)` takes a symbol value and returns the string key corresponding to it. Each is the other's inverse, so the following is `true`:

```js
Symbol.keyFor(Symbol.for("tokenString")) === "tokenString"; // true
```

Because registered symbols can be arbitrarily created anywhere, they behave almost exactly like the strings they wrap. Therefore, they are not guaranteed to be unique and are not garbage collectable. Therefore, registered symbols are disallowed in `WeakMap`, `WeakSet`, `WeakRef`, and `FinalizationRegistry` objects.

### Well-known Symbols

All static properties of the `Symbol` constructor are Symbols themselves, whose values are constant across realms. They are known as *well-known Symbols*, and their purpose is to serve as "protocols" for certain built-in JavaScript operations, allowing users to customize the language's behavior. For example, if a constructor function has a method with `Symbol.hasInstance` as its name, this method will encode its behavior with the `instanceof` operator.

Prior to well-known Symbols, JavaScript used normal properties to implement certain built-in operations. For example, the `JSON.stringify` function will attempt to call each object's `toJSON()` method, and the `String` function will call the object's `toString()` and `valueOf()` methods. However, as more operations are added to the language, designating each operation a "magic property" can break backward compatibility and make the language's behavior harder to reason with. Well-known Symbols allow the customizations to be "invisible" from normal code, which typically only read string properties.

In MDN and other sources, well-known symbol values are stylized by prefixing `@@`. For example, `Symbol.hasInstance` is written as `@@hasInstance`. This is because symbols don't have actual literal formats, but using `Symbol.hasInstance` does not reflect the ability of using other aliases to refer to the same symbol. This is like the difference between `Function.name` and `"Function"`.

Well-known symbols do not have the concept of garbage collectability, because they come in a fixed set and are unique throughout the lifetime of the program, similar to intrinsic objects such as `Array.prototype`, so they are also allowed in `WeakMap`, `WeakSet`, `WeakRef`, and `FinalizationRegistry` objects.

### Finding Symbol properties on objects

The method `Object.getOwnPropertySymbols()` returns an array of Symbols and lets you find Symbol properties on a given object. Note that every object is initialized with no own Symbol properties, so that this array will be empty unless you've set Symbol properties on the object.

Constructor
-----------

`Symbol()`

Creates a new `Symbol` object. It is not a constructor in the traditional sense, because it can only be called as a function, instead of being constructed with `new Symbol()`.

Static properties
-----------------

The static properties are all well-known Symbols. In these Symbols' descriptions, we will use language like "`Symbol.hasInstance` is a method determining…", but bear in mind that this is referring to the semantic of an object's method having this Symbol as the method name (because well-known Symbols act as "protocols"), not describing the value of the Symbol itself.

`Symbol.asyncIterator`

A method that returns the default AsyncIterator for an object. Used by `for await...of`.

`Symbol.hasInstance`

A method determining if a constructor object recognizes an object as its instance. Used by `instanceof`.

`Symbol.isConcatSpreadable`

A Boolean value indicating if an object should be flattened to its array elements. Used by `Array.prototype.concat()`.

`Symbol.iterator`

A method returning the default iterator for an object. Used by `for...of`.

`Symbol.match`

A method that matches against a string, also used to determine if an object may be used as a regular expression. Used by `String.prototype.match()`.

`Symbol.matchAll`

A method that returns an iterator, that yields matches of the regular expression against a string. Used by `String.prototype.matchAll()`.

`Symbol.replace`

A method that replaces matched substrings of a string. Used by `String.prototype.replace()`.

`Symbol.search`

A method that returns the index within a string that matches the regular expression. Used by `String.prototype.search()`.

`Symbol.species`

A constructor function that is used to create derived objects.

`Symbol.split`

A method that splits a string at the indices that match a regular expression. Used by `String.prototype.split()`.

`Symbol.toPrimitive`

A method converting an object to a primitive value.

`Symbol.toStringTag`

A string value used for the default description of an object. Used by `Object.prototype.toString()`.

`Symbol.unscopables`

An object value of whose own and inherited property names are excluded from the `with` environment bindings of the associated object.

Static methods
--------------

`Symbol.for()`

Searches for existing Symbols with the given `key` and returns it if found. Otherwise a new Symbol gets created in the global Symbol registry with `key`.

`Symbol.keyFor()`

Retrieves a shared Symbol key from the global Symbol registry for the given Symbol.

Instance properties
-------------------

These properties are defined on `Symbol.prototype` and shared by all `Symbol` instances.

`Symbol.prototype.constructor`

The constructor function that created the instance object. For `Symbol` instances, the initial value is the `Symbol` constructor.

`Symbol.prototype.description`

A read-only string containing the description of the Symbol.

`Symbol.prototype[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"Symbol"`. This property is used in `Object.prototype.toString()`. However, because `Symbol` also has its own `toString()` method, this property is not used unless you call `Object.prototype.toString.call()` with a symbol as `thisArg`.

Instance methods
----------------

`Symbol.prototype.toString()`

Returns a string containing the description of the Symbol. Overrides the `Object.prototype.toString()` method.

`Symbol.prototype.valueOf()`

Returns the Symbol. Overrides the `Object.prototype.valueOf()` method.

`Symbol.prototype[@@toPrimitive]()`

Returns the Symbol.

Examples
--------

### Using the typeof operator with Symbols

The `typeof` operator can help you to identify Symbols.

```js
typeof Symbol() === "symbol";
typeof Symbol("foo") === "symbol";
typeof Symbol.iterator === "symbol";
```

### Symbol type conversions

Some things to note when working with type conversion of Symbols.

* When trying to convert a Symbol to a number, a `TypeError` will be thrown
 (e.g. `+sym` or `sym | 0`).
* When using loose equality, `Object(sym) == sym` returns `true`.
* `Symbol("foo") + "bar"` throws a `TypeError` (can't convert Symbol to string). This prevents you from silently creating a new string property name from a Symbol, for example.
* The "safer" `String(sym)` conversion works like a call to `Symbol.prototype.toString()` with Symbols, but note that `new String(sym)` will throw.
### Symbols and for...in iteration

Symbols are not enumerable in `for...in` iterations. In addition, `Object.getOwnPropertyNames()` will not return Symbol object properties, however, you can use `Object.getOwnPropertySymbols()` to get these.

```js
const obj = {};

obj[Symbol("a")] = "a";
obj[Symbol.for("b")] = "b";
obj["c"] = "c";
obj.d = "d";

for (const i in obj) {
  console.log(i);
}
// "c" "d"
```

### Symbols and JSON.stringify()

Symbol-keyed properties will be completely ignored when using `JSON.stringify()`:

```js
JSON.stringify({ [Symbol("foo")]: "foo" });
// '{}'
```

For more details, see `JSON.stringify()`.

### Symbol wrapper objects as property keys

When a Symbol wrapper object is used as a property key, this object will be coerced to its wrapped Symbol:

```js
const sym = Symbol("foo");
const obj = { [sym]: 1 };
obj[sym]; // 1
obj[Object(sym)]; // still 1
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol-objects |

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

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

See also
--------

* Polyfill of `Symbol` in `core-js`
* `typeof`
* JavaScript data types and data structures
* ES6 In Depth: Symbols on hacks.mozilla.org (2015)


escape() - JavaScript

escape()
========

**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:** `escape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use `encodeURIComponent()` or `encodeURI()` if possible.

The **`escape()`** function computes a new string in which certain characters have been replaced by hexadecimal escape sequences.

Syntax
------

```js
escape(str)
```

### Parameters

`str`

A string to be encoded.

### Return value

A new string in which certain characters have been escaped.

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

`escape()` is a function property of the global object.

The `escape()` function replaces all characters with escape sequences, with the exception of ASCII word characters (A–Z, a–z, 0–9, \_) and `@\*_+-./`. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number in the format `%XX`, left-padded with 0 if necessary. Otherwise, it is represented by a four-digit hexadecimal number in the format `%uXXXX`, left-padded with 0 if necessary.

**Note:** This function was used mostly for URL encoding and is partly based on the escape format in RFC 1738. The escape format is *not* an escape sequence in string literals. You can replace `%XX` with `\xXX` and `%uXXXX` with `\uXXXX` to get a string containing actual string-literal escape sequences.

Examples
--------

### Using escape()

```js
escape("abc123"); // "abc123"
escape("äöü"); // "%E4%F6%FC"
escape("ć"); // "%u0107"

// special characters
escape("@\*\_+-./"); // "@\*\_+-./"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-escape-string |

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

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

See also
--------

* Polyfill of `escape` in `core-js`
* `encodeURI`
* `encodeURIComponent`
* `unescape`


AsyncIterator.prototype[@@asyncIterator]() - JavaScript

AsyncIterator.prototype[@@asyncIterator]()
==========================================

The **`[@@asyncIterator]()`** method of `AsyncIterator` instances implements the async iterable protocol and allows built-in async iterators to be consumed by most syntaxes expecting async iterables, such as `for await...of` loops. It returns the value of `this`, which is the async iterator object itself.

Try it
------

Syntax
------

```js
asyncIterator[Symbol.asyncIterator]()
```

### Parameters

None.

### Return value

The value of `this`, which is the async iterator object itself.

Examples
--------

### Iteration using for await...of loop

Note that you seldom need to call this method directly. The existence of the `@@asyncIterator` method makes all built-in async iterators async iterable, and iterating syntaxes like the `for await...of` loop automatically calls this method to obtain the async iterator to loop over.

```js
const asyncIterator = (async function\* () {
  yield 1;
  yield 2;
  yield 3;
})();
(async () => {
  for await (const value of asyncIterator) {
    console.log(value);
  }
})();
// Logs: 1, 2, 3
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-asynciteratorprototype-asynciterator |

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

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

See also
--------

* `for await...of`


Int16Array() constructor - JavaScript

Int16Array() constructor
========================

The **`Int16Array()`** constructor creates `Int16Array` objects. The contents are initialized to `0`.

Syntax
------

```js
new Int16Array()
new Int16Array(length)
new Int16Array(typedArray)
new Int16Array(object)

new Int16Array(buffer)
new Int16Array(buffer, byteOffset)
new Int16Array(buffer, byteOffset, length)
```

**Note:** `Int16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`.

### Parameters

See `TypedArray`.

### Exceptions

See `TypedArray`.

Examples
--------

### Different ways to create an Int16Array

```js
// From a length
const int16 = new Int16Array(2);
int16[0] = 42;
console.log(int16[0]); // 42
console.log(int16.length); // 2
console.log(int16.BYTES\_PER\_ELEMENT); // 2

// From an array
const x = new Int16Array([21, 31]);
console.log(x[1]); // 31

// From another TypedArray
const y = new Int16Array(x);
console.log(y[0]); // 21

// From an ArrayBuffer
const buffer = new ArrayBuffer(16);
const z = new Int16Array(buffer, 2, 4);
console.log(z.byteOffset); // 2

// From an iterable
const iterable = (function\* () {
  yield\* [1, 2, 3];
})();
const int16FromIterable = new Int16Array(iterable);
console.log(int16FromIterable);
// Int16Array [1, 2, 3]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-typedarray-constructors |

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

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

See also
--------

* Polyfill of `Int16Array` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `ArrayBuffer`
* `DataView`


Boolean.prototype.toString() - JavaScript

Boolean.prototype.toString()
============================

The **`toString()`** method of `Boolean` values returns a string representing the specified boolean value.

Try it
------

Syntax
------

```js
toString()
```

### Parameters

None.

### Return value

A string representing the specified boolean value.

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

 The `Boolean` object overrides the `toString` method of `Object`; it does not inherit
 `Object.prototype.toString()`. For `Boolean` values, the `toString` method returns a string representation of the boolean value, which is either `"true"` or `"false"`.

The `toString()` method requires its `this` value to be a `Boolean` primitive or wrapper object. It throws a `TypeError` for other `this` values without attempting to coerce them to boolean values.

Because `Boolean` doesn't have a `[@@toPrimitive]()` method, JavaScript calls the `toString()` method automatically when a `Boolean` *object* is used in a context expecting a string, such as in a template literal. However, boolean *primitive* values do not consult the `toString()` method to be coerced to strings — rather, they are directly converted using the same algorithm as the initial `toString()` implementation.

```js
Boolean.prototype.toString = () => "Overridden";
console.log(`${true}`); // "true"
console.log(`${new Boolean(true)}`); // "Overridden"
```

Examples
--------

### Using toString()

```js
const flag = new Boolean(true);
console.log(flag.toString()); // "true"
console.log(false.toString()); // "false"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-boolean.prototype.tostring |

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

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

See also
--------

* `Object.prototype.toString()`


Boolean() constructor - JavaScript

Boolean() constructor
=====================

The **`Boolean()`** constructor creates `Boolean` objects. When called as a function, it returns primitive values of type Boolean.

Try it
------

Syntax
------

```js
new Boolean(value)
Boolean(value)
```

**Note:** `Boolean()` can be called with or without `new`, but with different effects. See Return value.

### Parameters

`value`

The initial value of the `Boolean` object.

### Return value

When `Boolean()` is called as a constructor (with `new`), it creates a `Boolean` object, which is **not** a primitive.

When `Boolean()` is called as a function (without `new`), it coerces the parameter to a boolean primitive.

**Warning:** You should rarely find yourself using `Boolean` as a constructor.

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

The value passed as the first parameter is converted to a boolean value. If the value is omitted or is `0`, `-0`, `0n`, `null`, `false`, `NaN`, `undefined`, or the empty string (`""`), then the object has an initial value of `false`. All other values, including any object, an empty array (`[]`), or the string `"false"`, create an object with an initial value of `true`.

**Note:** When the non-standard property `document.all` is used as an argument for this constructor, the result is a `Boolean` object with the value `false`. This property is legacy and non-standard and should not be used.

Examples
--------

### Creating Boolean objects with an initial value of false

```js
const bZero = new Boolean(0);
const bNull = new Boolean(null);
const bEmptyString = new Boolean("");
const bfalse = new Boolean(false);

typeof bfalse; // "object"
Boolean(bfalse); // true
```

Note how converting a `Boolean` object to a primitive with `Boolean()` always yields `true`, even if the object holds a value of `false`. You are therefore always advised to avoid constructing `Boolean` wrapper objects.

If you need to take the primitive value out from the wrapper object, instead of using the `Boolean()` function, use the object's `valueOf()` method instead.

```js
const bfalse = new Boolean(false);

bfalse.valueOf(); // false
```

### Creating `Boolean` objects with an initial value of `true`

```js
const btrue = new Boolean(true);
const btrueString = new Boolean("true");
const bfalseString = new Boolean("false");
const bSuLin = new Boolean("Su Lin");
const bArrayProto = new Boolean([]);
const bObjProto = new Boolean({});
```

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

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

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

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

See also
--------

* Boolean


Boolean.prototype.valueOf() - JavaScript

Boolean.prototype.valueOf()
===========================

 The **`valueOf()`** method of `Boolean` values returns the primitive value of a
 `Boolean` object.

Try it
------

Syntax
------

```js
valueOf()
```

### Parameters

None.

### Return value

The primitive value of the given `Boolean` object.

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

 The `valueOf()` method of `Boolean` returns the primitive value
 of a `Boolean` object or literal `Boolean` as a Boolean data type.

This method is usually called internally by JavaScript and not explicitly in code.

Examples
--------

### Using `valueOf()`

```js
x = new Boolean();
myVar = x.valueOf(); // assigns false to myVar
```

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

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

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

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

See also
--------

* `Object.prototype.valueOf()`


Object.setPrototypeOf() - JavaScript

Object.setPrototypeOf()
=======================

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

**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 `Object.setPrototypeOf(...)` 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.

Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the `[[Prototype]]` of an object. Instead, create a new object with the desired `[[Prototype]]` using `Object.create()`.

Try it
------

Syntax
------

```js
Object.setPrototypeOf(obj, prototype)
```

### Parameters

`obj`

The object which is to have its prototype set.

`prototype`

The object's new prototype (an object or `null`).

### Return value

The specified object.

### Exceptions

`TypeError`

Thrown in one of the following cases:

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

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

`Object.setPrototypeOf()` is generally considered the proper way to set the prototype of an object. You should always use it in favor of the deprecated `Object.prototype.__proto__` accessor.

If the `obj` parameter is not an object (e.g. number, string, etc.), this method does nothing — without coercing it to an object or attempting to set its prototype — and directly returns `obj` as a primitive value. If `prototype` is the same value as the prototype of `obj`, then `obj` is directly returned, without causing a `TypeError` even when `obj` has immutable prototype.

For security concerns, there are certain built-in objects that are designed to have an *immutable prototype*. This prevents prototype pollution attacks, especially proxy-related ones. The core language only specifies `Object.prototype` as an immutable prototype exotic object, whose prototype is always `null`. In browsers, `window` and `location` are two other very common examples.

```js
Object.isExtensible(Object.prototype); // true; you can add more properties
Object.setPrototypeOf(Object.prototype, {}); // TypeError: Immutable prototype object '#<Object>' cannot have their prototype set
Object.setPrototypeOf(Object.prototype, null); // No error; the prototype of `Object.prototype` is already `null`
```

Examples
--------

### Pseudoclassical inheritance using Object.setPrototypeOf()

Inheritance in JS using classes.

```js
class Human {}
class SuperHero extends Human {}

const superMan = new SuperHero();
```

However, if we want to implement subclasses without using `class`, we can do the following:

```js
function Human(name, level) {
  this.name = name;
  this.level = level;
}

function SuperHero(name, level) {
  Human.call(this, name, level);
}

Object.setPrototypeOf(SuperHero.prototype, Human.prototype);

// Set the `[[Prototype]]` of `SuperHero.prototype`
// to `Human.prototype`
// To set the prototypal inheritance chain

Human.prototype.speak = function () {
  return `${this.name} says hello.`;
};

SuperHero.prototype.fly = function () {
  return `${this.name} is flying.`;
};

const superMan = new SuperHero("Clark Kent", 1);

console.log(superMan.fly());
console.log(superMan.speak());
```

The similarity between classical inheritance (with classes) and pseudoclassical inheritance (with constructors' `prototype` property) as done above is mentioned in Inheritance chains.

Since function constructors' `prototype` property is writable, you can reassign it to a new object created with `Object.create()` to achieve the same inheritance chain as well. There are caveats to watch out when using `create()`, such as remembering to re-add the `constructor` property.

In the example below, which also uses classes, `SuperHero` is made to inherit from `Human` without using `extends` by using `setPrototypeOf()` instead.

**Warning:** It is not advisable to use `setPrototypeOf()` instead of `extends` due to performance and readability reasons.

```js
class Human {}
class SuperHero {}

// Set the instance properties
Object.setPrototypeOf(SuperHero.prototype, Human.prototype);

// Hook up the static properties
Object.setPrototypeOf(SuperHero, Human);

const superMan = new SuperHero();
```

Subclassing without `extends` is mentioned in ES-6 subclassing.

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

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

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

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

See also
--------

* Polyfill of `Object.setPrototypeOf` in `core-js`
* `Reflect.setPrototypeOf()`
* `Object.prototype.isPrototypeOf()`
* `Object.getPrototypeOf()`
* `Object.prototype.__proto__`
* Inheritance chain
* ES6 In Depth: Subclassing on hacks.mozilla.org (2015)


Object.isExtensible() - JavaScript

Object.isExtensible()
=====================

 The **`Object.isExtensible()`** static method determines if an object
 is extensible (whether it can have new properties added to it).

Try it
------

Syntax
------

```js
Object.isExtensible(obj)
```

### Parameters

`obj`

The object which should be checked.

### Return value

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

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

Objects are extensible by default: they can have new properties added to them, and their `[[Prototype]]` can be re-assigned. An object can be marked as non-extensible using one of `Object.preventExtensions()`, `Object.seal()`, `Object.freeze()`, or `Reflect.preventExtensions()`.

Examples
--------

### Using Object.isExtensible

```js
// New objects are extensible.
const empty = {};
Object.isExtensible(empty); // true

// They can be made un-extensible
Object.preventExtensions(empty);
Object.isExtensible(empty); // false

// Sealed objects are by definition non-extensible.
const sealed = Object.seal({});
Object.isExtensible(sealed); // false

// Frozen objects are also by definition non-extensible.
const frozen = Object.freeze({});
Object.isExtensible(frozen); // false
```

### 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 `false` without any errors if a non-object argument is passed, since primitives are, by definition, immutable.

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

Object.isExtensible(1);
// false (ES2015 code)
```

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

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

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

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

See also
--------

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


Object.groupBy() - JavaScript

Object.groupBy()
================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback

**Note:** In some versions of some browsers, this method was implemented as the method `Array.prototype.group()`. Due to web compatibility issues, it is now implemented as a static method. Check the browser compatibility table for details.

The **`Object.groupBy()`** static method groups the elements of a given iterable according to the string values returned by a provided callback function. The returned object has separate properties for each group, containing arrays with the elements in the group.

This method should be used when group names can be represented by strings. If you need to group elements using a key that is some arbitrary value, use `Map.groupBy()` instead.

Syntax
------

```js
Object.groupBy(items, callbackFn)
```

### Parameters

`items`

An iterable (such as an `Array`) whose elements will be grouped.

`callbackFn`

A function to execute for each element in the iterable. It should return a value that can get coerced into a property key (string or symbol) indicating the group of the current element. The function is called with the following arguments:

`element`

The current element being processed.

`index`

The index of the current element being processed.

### Return value

A `null`-prototype object with properties for all groups, each assigned to an array containing the elements of the associated group.

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

`Object.groupBy()` calls a provided `callbackFn` function once for each element in an iterable. The callback function should return a string or symbol (values that are neither type are coerced to strings) indicating the group of the associated element. The values returned by `callbackFn` are used as keys for the object returned by `Map.groupBy()`. Each key has an associated array containing all the elements for which the callback returned the same value.

The elements in the returned object and the original iterable are the same (not deep copies). Changing the internal structure of the elements will be reflected in both the original iterable and the returned object.

Examples
--------

### Using Object.groupBy()

First we define an array containing objects representing an inventory of different foodstuffs. Each food has a `type` and a `quantity`.

```js
const inventory = [
  { name: "asparagus", type: "vegetables", quantity: 5 },
  { name: "bananas", type: "fruit", quantity: 0 },
  { name: "goat", type: "meat", quantity: 23 },
  { name: "cherries", type: "fruit", quantity: 5 },
  { name: "fish", type: "meat", quantity: 22 },
];
```

The code below groups the elements by the value of their `type` property.

```js
const result = Object.groupBy(inventory, ({ type }) => type);

/\* Result is:
{
 vegetables: [
 { name: 'asparagus', type: 'vegetables', quantity: 5 },
 ],
 fruit: [
 { name: "bananas", type: "fruit", quantity: 0 },
 { name: "cherries", type: "fruit", quantity: 5 }
 ],
 meat: [
 { name: "goat", type: "meat", quantity: 23 },
 { name: "fish", type: "meat", quantity: 22 }
 ]
}
\*/
```

 The arrow function just returns the `type` of each array element each time it is called. Note that the function argument `{ type }` is a basic example of object destructuring syntax for function arguments. This unpacks the `type` property of an object passed as a parameter, and assigns it to a variable named `type` in the body of the function.
 This is a very succinct way to access the relevant values of elements within a function.

We can also create groups inferred from values in one or more properties of the elements. Below is a very similar example that puts the items into `ok` or `restock` groups based on the value of the `quantity` field.

```js
function myCallback({ quantity }) {
  return quantity > 5 ? "ok" : "restock";
}

const result2 = Object.groupBy(inventory, myCallback);

/\* Result is:
{
 restock: [
 { name: "asparagus", type: "vegetables", quantity: 5 },
 { name: "bananas", type: "fruit", quantity: 0 },
 { name: "cherries", type: "fruit", quantity: 5 }
 ],
 ok: [
 { name: "goat", type: "meat", quantity: 23 },
 { name: "fish", type: "meat", quantity: 22 }
 ]
}
\*/
```

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

| Specification |
| --- |
| Array Grouping # sec-object.groupby |

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

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

See also
--------

* Polyfill of `Object.groupBy` in `core-js`
* Indexed collections guide
* `Array.prototype.reduce()`
* `Object.fromEntries()`
* `Map.groupBy()`


Object.fromEntries() - JavaScript

Object.fromEntries()
====================

The **`Object.fromEntries()`** static method transforms a list of key-value pairs into an object.

Try it
------

Syntax
------

```js
Object.fromEntries(iterable)
```

### Parameters

`iterable`

An iterable, such as an `Array` or `Map`, containing a list of objects. Each object should have two properties:

`0`

A string or symbol representing the property key.

`1`

The property value.

Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value.

### Return value

A new object whose properties are given by the entries of the iterable.

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

The `Object.fromEntries()` method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The `iterable` argument is expected to be an object that implements an `@@iterator` method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key.

`Object.fromEntries()` performs the reverse of `Object.entries()`, except that `Object.entries()` only returns string-keyed properties, while `Object.fromEntries()` can also create symbol-keyed properties.

**Note:** Unlike `Array.from()`, `Object.fromEntries()` does not use the value of `this`, so calling it on another constructor does not create objects of that type.

Examples
--------

### Converting a Map to an Object

With `Object.fromEntries`, you can convert from `Map` to `Object`:

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

### Converting an Array to an Object

With `Object.fromEntries`, you can convert from `Array` to `Object`:

```js
const arr = [
  ["0", "a"],
  ["1", "b"],
  ["2", "c"],
];
const obj = Object.fromEntries(arr);
console.log(obj); // { 0: "a", 1: "b", 2: "c" }
```

### Object transformations

With `Object.fromEntries`, its reverse method `Object.entries()`, and array manipulation methods, you are able to transform objects like this:

```js
const object1 = { a: 1, b: 2, c: 3 };

const object2 = Object.fromEntries(
  Object.entries(object1).map(([key, val]) => [key, val \* 2]),
);

console.log(object2);
// { a: 2, b: 4, c: 6 }
```

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

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

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

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

See also
--------

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


Object.getOwnPropertyDescriptors() - JavaScript

Object.getOwnPropertyDescriptors()
==================================

 The **`Object.getOwnPropertyDescriptors()`** static method returns all
 own property descriptors of a given object.

Try it
------

Syntax
------

```js
Object.getOwnPropertyDescriptors(obj)
```

### Parameters

`obj`

The object for which to get all own property descriptors.

### Return value

 An object containing all own property descriptors of an object. Might be an empty
 object, if there are no properties.

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

 This method permits examination of the precise description of all own properties of an
 object. A *property* in JavaScript consists of either a string-valued name or a
 `Symbol` and a property descriptor. Further information about property
 descriptor types and their attributes can be found in
 `Object.defineProperty()`.

A *property descriptor* is a record with some of the following attributes:

`value`

The value associated with the property (data descriptors only).

`writable`

`true` if and only if the value associated with the property may be
 changed (data descriptors only).

`get`

 A function which serves as a getter for the property, or `undefined` if
 there is no getter (accessor descriptors only).

`set`

 A function which serves as a setter for the property, or `undefined` if
 there is no setter (accessor descriptors only).

`configurable`

`true` if and only if the type of this property descriptor may be changed
 and if the property may be deleted from the corresponding object.

`enumerable`

`true` if and only if this property shows up during enumeration of the
 properties on the corresponding object.

Examples
--------

### Creating a shallow copy

 Whereas the `Object.assign()` method will only copy enumerable and own
 properties from a source object to a target object, you are able to use this method and
 `Object.create()` for a shallow copy between two unknown objects:

```js
Object.create(
  Object.getPrototypeOf(obj),
  Object.getOwnPropertyDescriptors(obj),
);
```

### Creating a subclass

 A typical way of creating a subclass is to define the subclass, set its prototype to an
 instance of the superclass, and then define properties on that instance. This can get
 awkward especially for getters and setters. Instead, you can use this code to set the
 prototype:

```js
function superclass() {}
superclass.prototype = {
  // Define the superclass constructor, methods, and properties here
};
function subclass() {}
subclass.prototype = Object.create(superclass.prototype, {
  // Define the subclass constructor, methods, and properties here
});
```

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

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

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

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

See also
--------

* Polyfill of `Object.getOwnPropertyDescriptors` in `core-js`
* `Object.getOwnPropertyDescriptor()`
* `Object.defineProperty()`


Object.values() - JavaScript

Object.values()
===============

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

Try it
------

Syntax
------

```js
Object.values(obj)
```

### Parameters

`obj`

An object.

### Return value

An array containing the given object's own enumerable string-keyed property values.

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

`Object.values()` returns an array whose elements are values of enumerable string-keyed properties 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.values()` is the same as that provided by a `for...in` loop.

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

Examples
--------

### Using Object.values()

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

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

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

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

### Using Object.values() 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.values("foo")); // ['f', 'o', 'o']

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

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

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

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

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

See also
--------

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


Object.prototype.__lookupSetter__() - JavaScript

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

**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 **`__lookupSetter__()`** method of `Object` instances returns the function bound as a setter to the specified property.

Syntax
------

```js
\_\_lookupSetter\_\_(prop)
```

### Parameters

`prop`

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

### Return value

The function bound as a setter 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 `__lookupSetter__()` method. If a setter has been defined for an object's property, it's not possible to reference the setter function through that property, because that property only calls the function when it's being set. `__lookupSetter__()` can be used to obtain a reference to the setter function.

`__lookupSetter__()` walks up the prototype chain to find the specified property. If any object along the prototype chain has the specified own property, the `set` 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.

`__lookupSetter__()` 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 `__lookupSetter__()`, it also needs to implement the `__lookupGetter__()`, `__defineGetter__()`, and `__defineSetter__()` methods.

Examples
--------

### Using \_\_lookupSetter\_\_()

```js
const obj = {
  set foo(value) {
    this.bar = value;
  },
};

obj.\_\_lookupSetter\_\_("foo");
// [Function: set foo]
```

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

You should use the `Object.getOwnPropertyDescriptor()` API to look up a property's setter. Compared to `__lookupSetter__()`, 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 `__lookupSetter__()` method. If `__lookupSetter__()`'s behavior of walking up the prototype chain is important, you may implement it yourself with `Object.getPrototypeOf()`.

```js
const obj = {
  set foo(value) {
    this.bar = value;
  },
};

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

```js
const obj2 = {
  \_\_proto\_\_: {
    set foo(value) {
      this.bar = value;
    },
  },
};

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

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

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

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

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

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

See also
--------

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


Object.getOwnPropertyDescriptor() - JavaScript

Object.getOwnPropertyDescriptor()
=================================

 The **`Object.getOwnPropertyDescriptor()`** static method returns an
 object describing the configuration of a specific property on a given object (that is,
 one directly present on an object and not in the object's prototype chain). The object
 returned is mutable but mutating it has no effect on the original property's
 configuration.

Try it
------

Syntax
------

```js
Object.getOwnPropertyDescriptor(obj, prop)
```

### Parameters

`obj`

The object in which to look for the property.

`prop`

 The name or `Symbol` of the property whose description is to be
 retrieved.

### Return value

 A property descriptor of the given property if it exists on the object,
 `undefined` otherwise.

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

 This method permits examination of the precise description of a property. A
 *property* in JavaScript consists of either a string-valued name or a
 `Symbol` and a property descriptor. Further information about property
 descriptor types and their attributes can be found in
 `Object.defineProperty()`.

A *property descriptor* is a record with some of the following attributes:

`value`

The value associated with the property (data descriptors only).

`writable`

`true` if and only if the value associated with the property may be
 changed (data descriptors only).

`get`

 A function which serves as a getter for the property, or `undefined` if
 there is no getter (accessor descriptors only).

`set`

 A function which serves as a setter for the property, or `undefined` if
 there is no setter (accessor descriptors only).

`configurable`

`true` if and only if the type of this property descriptor may be changed
 and if the property may be deleted from the corresponding object.

`enumerable`

`true` if and only if this property shows up during enumeration of the
 properties on the corresponding object.

Examples
--------

### Using Object.getOwnPropertyDescriptor()

```js
let o, d;

o = {
  get foo() {
    return 17;
  },
};
d = Object.getOwnPropertyDescriptor(o, "foo");
console.log(d);
// {
// configurable: true,
// enumerable: true,
// get: [Function: get foo],
// set: undefined
// }

o = { bar: 42 };
d = Object.getOwnPropertyDescriptor(o, "bar");
console.log(d);
// {
// configurable: true,
// enumerable: true,
// value: 42,
// writable: true
// }

o = { [Symbol.for("baz")]: 73 };
d = Object.getOwnPropertyDescriptor(o, Symbol.for("baz"));
console.log(d);
// {
// configurable: true,
// enumerable: true,
// value: 73,
// writable: true
// }

o = {};
Object.defineProperty(o, "qux", {
  value: 8675309,
  writable: false,
  enumerable: false,
});
d = Object.getOwnPropertyDescriptor(o, "qux");
console.log(d);
// {
// value: 8675309,
// writable: false,
// enumerable: false,
// configurable: false
// }
```

### Non-object coercion

 In ES5, if the first argument to this method is not an object (a primitive), then it
 will cause a `TypeError`. In ES2015, a non-object first argument will be
 coerced to an object at first.

```js
Object.getOwnPropertyDescriptor("foo", 0);
// TypeError: "foo" is not an object // ES5 code

Object.getOwnPropertyDescriptor("foo", 0);
// Object returned by ES2015 code: {
// configurable: false,
// enumerable: true,
// value: "f",
// writable: false
// }
```

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

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

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

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

See also
--------

* `Object.defineProperty()`
* `Reflect.getOwnPropertyDescriptor()`


Object.prototype.toString() - JavaScript

Object.prototype.toString()
===========================

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

Try it
------

Syntax
------

```js
toString()
```

### Parameters

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

### Return value

A string representing the object.

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

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

This method is called in priority by string conversion, but numeric conversion and primitive conversion call `valueOf()` in priority. However, because the base `valueOf()` method returns an object, the `toString()` method is usually called in the end, unless the object overrides `valueOf()`. For example, `+[1]` returns `1`, because its `toString()` method returns `"1"`, which is then converted to a number.

All objects that inherit from `Object.prototype` (that is, all except `null`-prototype objects) inherit the `toString()` method. When you create a custom object, you can override `toString()` to call a custom method, so that your custom object can be converted to a string value. 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.

To use the base `Object.prototype.toString()` with an object that has it overridden (or to invoke it on `null` or `undefined`), you need to call `Function.prototype.call()` or `Function.prototype.apply()` on it, passing the object you want to inspect as the first parameter (called `thisArg`).

```js
const arr = [1, 2, 3];

arr.toString(); // "1,2,3"
Object.prototype.toString.call(arr); // "[object Array]"
```

`Object.prototype.toString()` returns `"[object Type]"`, where `Type` is the object type. If the object has a `Symbol.toStringTag` property whose value is a string, that value will be used as the `Type`. Many built-in objects, including `Map` and `Symbol`, have a `Symbol.toStringTag`. Some objects predating ES6 do not have `Symbol.toStringTag`, but have a special tag nonetheless. They include (the tag is the same as the type name given below):

* `Array`
* `Function` (anything whose `typeof` returns `"function"`)
* `Error`
* `Boolean`
* `Number`
* `String`
* `Date`
* `RegExp`

The `arguments` object returns `"[object Arguments]"`. Everything else, including user-defined classes, unless with a custom `Symbol.toStringTag`, will return `"[object Object]"`.

`Object.prototype.toString()` invoked on `null` and `undefined` returns `[object Null]` and `[object Undefined]`, respectively.

Examples
--------

### Overriding toString for custom objects

You can create a function to be called in place of the default `toString()` method. The `toString()` function you create should return a string value. If it returns an object and the method is called implicitly during type conversion, then its result is ignored and the value of a related method, `valueOf()`, is used instead, or a `TypeError` is thrown if none of these methods return a primitive.

The following code defines a `Dog` class.

```js
class Dog {
  constructor(name, breed, color, sex) {
    this.name = name;
    this.breed = breed;
    this.color = color;
    this.sex = sex;
  }
}
```

If you call the `toString()` method, either explicitly or implicitly, on an instance of `Dog`, it returns the default value inherited from `Object`:

```js
const theDog = new Dog("Gabby", "Lab", "chocolate", "female");

theDog.toString(); // "[object Object]"
`${theDog}`; // "[object Object]"
```

The following code overrides the default `toString()` method. This method generates a string containing the `name`, `breed`, `color`, and `sex` of the object.

```js
class Dog {
  constructor(name, breed, color, sex) {
    this.name = name;
    this.breed = breed;
    this.color = color;
    this.sex = sex;
  }
  toString() {
    return `Dog ${this.name} is a ${this.sex} ${this.color} ${this.breed}`;
  }
}
```

With the preceding code in place, any time an instance of `Dog` is used in a string context, JavaScript automatically calls the `toString()` method.

```js
const theDog = new Dog("Gabby", "Lab", "chocolate", "female");

`${theDog}`; // "Dog Gabby is a female chocolate Lab"
```

### Using toString() to detect object class

`toString()` can be used with every object and (by default) allows you to get its class.

```js
const toString = Object.prototype.toString;

toString.call(new Date()); // [object Date]
toString.call(new String()); // [object String]
// Math has its Symbol.toStringTag
toString.call(Math); // [object Math]

toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]
```

Using `toString()` in this way is unreliable; objects can change the behavior of `Object.prototype.toString()` by defining a `Symbol.toStringTag` property, leading to unexpected results. For example:

```js
const myDate = new Date();
Object.prototype.toString.call(myDate); // [object Date]

myDate[Symbol.toStringTag] = "myDate";
Object.prototype.toString.call(myDate); // [object myDate]

Date.prototype[Symbol.toStringTag] = "prototype polluted";
Object.prototype.toString.call(new Date()); // [object prototype polluted]
```

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

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

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

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

See also
--------

* Polyfill of `Object.prototype.toString` with `Symbol.toStringTag` support in `core-js`
* `Object.prototype.valueOf()`
* `Number.prototype.toString()`
* `Symbol.toPrimitive`
* `Symbol.toStringTag`


Object.prototype.constructor - JavaScript

Object.prototype.constructor
============================

The **`constructor`** data property of an `Object` instance returns a reference to the constructor function that created the instance object. Note that the value of this property is a reference to *the function itself*, not a string containing the function's name.

**Note:** This is a property of JavaScript objects. For the `constructor` method in classes, see its own reference page.

Value
-----

A reference to the constructor function that created the instance object.

| Property attributes of `Object.prototype.constructor` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |

**Note:** This property is created by default on the `prototype` property of every constructor function and is inherited by all objects created by that constructor.

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

Any object (with the exception of `null` prototype objects) will have a `constructor` property on its `[[Prototype]]`. Objects created with literals will also have a `constructor` property that points to the constructor type for that object — for example, array literals create `Array` objects, and object literals create plain objects.

```js
const o1 = {};
o1.constructor === Object; // true

const o2 = new Object();
o2.constructor === Object; // true

const a1 = [];
a1.constructor === Array; // true

const a2 = new Array();
a2.constructor === Array; // true

const n = 3;
n.constructor === Number; // true
```

Note that `constructor` usually comes from the constructor's `prototype` property. If you have a longer prototype chain, you can usually expect every object in the chain to have a `constructor` property.

```js
const o = new TypeError(); // Inheritance: TypeError -> Error -> Object
const proto = Object.getPrototypeOf;
proto(o).constructor === TypeError; // true
proto(proto(o)).constructor === Error; // true
proto(proto(proto(o))).constructor === Object; // true
```

Examples
--------

### Displaying the constructor of an object

The following example creates a constructor (`Tree`) and an object of that type (`theTree`). The example then displays the `constructor` property for the object `theTree`.

```js
function Tree(name) {
  this.name = name;
}

const theTree = new Tree("Redwood");
console.log(`theTree.constructor is ${theTree.constructor}`);
```

This example displays the following output:
```

theTree.constructor is function Tree(name) {
  this.name = name;
}
```

### Assigning the constructor property to an object

One can assign the `constructor` property of non-primitives.

```js
const arr = [];
arr.constructor = String;
arr.constructor === String; // true
arr instanceof String; // false
arr instanceof Array; // true

const foo = new Foo();
foo.constructor = "bar";
foo.constructor === "bar"; // true

// etc.
```

This does not overwrite the old `constructor` property — it was originally present on the instance's `[[Prototype]]`, not as its own property.

```js
const arr = [];
Object.hasOwn(arr, "constructor"); // false
Object.hasOwn(Object.getPrototypeOf(arr), "constructor"); // true

arr.constructor = String;
Object.hasOwn(arr, "constructor"); // true — the instance property shadows the one on its prototype
```

But even when `Object.getPrototypeOf(a).constructor` is re-assigned, it won't change other behaviors of the object. For example, the behavior of `instanceof` is controlled by `Symbol.hasInstance`, not `constructor`:

```js
const arr = [];
arr.constructor = String;
arr instanceof String; // false
arr instanceof Array; // true
```

There is nothing protecting the `constructor` property from being re-assigned or shadowed, so using it to detect the type of a variable should usually be avoided in favor of less fragile ways like `instanceof` and `Symbol.toStringTag` for objects, or `typeof` for primitives.

### Changing the constructor of a constructor function's prototype

Every constructor has a `prototype` property, which will become the instance's `[[Prototype]]` when called via the `new` operator. `ConstructorFunction.prototype.constructor` will therefore become a property on the instance's `[[Prototype]]`, as previously demonstrated.

However, if `ConstructorFunction.prototype` is re-assigned, the `constructor` property will be lost. For example, the following is a common way to create an inheritance pattern:

```js
function Parent() {
  // …
}
Parent.prototype.parentMethod = function () {};

function Child() {
  Parent.call(this); // Make sure everything is initialized properly
}
// Pointing the [[Prototype]] of Child.prototype to Parent.prototype
Child.prototype = Object.create(Parent.prototype);
```

The `constructor` of instances of `Child` will be `Parent` due to `Child.prototype` being re-assigned.

This is usually not a big deal — the language almost never reads the `constructor` property of an object. The only exception is when using `@@species` to create new instances of a class, but such cases are rare, and you should be using the `extends` syntax to subclass builtins anyway.

However, ensuring that `Child.prototype.constructor` always points to `Child` itself is crucial when some caller is using `constructor` to access the original class from an instance. Take the following case: the object has the `create()` method to create itself.

```js
function Parent() {
  // …
}
function CreatedConstructor() {
  Parent.call(this);
}

CreatedConstructor.prototype = Object.create(Parent.prototype);

CreatedConstructor.prototype.create = function () {
  return new this.constructor();
};

new CreatedConstructor().create().create(); // TypeError: new CreatedConstructor().create().create is undefined, since constructor === Parent
```

In the example above, an exception is thrown, since the `constructor` links to `Parent`. To avoid this, just assign the necessary constructor you are going to use.

```js
function Parent() {
  // …
}
function CreatedConstructor() {
  // …
}

CreatedConstructor.prototype = Object.create(Parent.prototype, {
  // Return original constructor to Child
  constructor: {
    value: CreatedConstructor,
    enumerable: false, // Make it non-enumerable, so it won't appear in `for...in` loop
    writable: true,
    configurable: true,
  },
});

CreatedConstructor.prototype.create = function () {
  return new this.constructor();
};

new CreatedConstructor().create().create(); // it's pretty fine
```

Note that when manually adding the `constructor` property, it's crucial to make the property non-enumerable, so `constructor` won't be visited in `for...in` loops — as it normally isn't.

If the code above looks like too much boilerplate, you may also consider using `Object.setPrototypeOf()` to manipulate the prototype chain.

```js
function Parent() {
  // …
}
function CreatedConstructor() {
  // …
}

Object.setPrototypeOf(CreatedConstructor.prototype, Parent.prototype);

CreatedConstructor.prototype.create = function () {
  return new this.constructor();
};

new CreatedConstructor().create().create(); // still works without re-creating constructor property
```

`Object.setPrototypeOf()` comes with its potential performance downsides because all previously created objects involved in the prototype chain have to be re-compiled; but if the above initialization code happens before `Parent` or `CreatedConstructor` are constructed, the effect should be minimal.

Let's consider one more involved case.

```js
function ParentWithStatic() {}

ParentWithStatic.startPosition = { x: 0, y: 0 }; // Static member property
ParentWithStatic.getStartPosition = function () {
  return this.startPosition;
};

function Child(x, y) {
  this.position = { x, y };
}

Child.prototype = Object.create(ParentWithStatic.prototype, {
  // Return original constructor to Child
  constructor: {
    value: Child,
    enumerable: false,
    writable: true,
    configurable: true,
  },
});

Child.prototype.getOffsetByInitialPosition = function () {
  const position = this.position;
  // Using this.constructor, in hope that getStartPosition exists as a static method
  const startPosition = this.constructor.getStartPosition();

  return {
    offsetX: startPosition.x - position.x,
    offsetY: startPosition.y - position.y,
  };
};

new Child(1, 1).getOffsetByInitialPosition();
// Error: this.constructor.getStartPosition is undefined, since the
// constructor is Child, which doesn't have the getStartPosition static method
```

For this example to work properly, we can reassign the `Parent`'s static properties to `Child`:

```js
// …
Object.assign(Child, ParentWithStatic); // Notice that we assign it before we create() a prototype below
Child.prototype = Object.create(ParentWithStatic.prototype, {
  // Return original constructor to Child
  constructor: {
    value: Child,
    enumerable: false,
    writable: true,
    configurable: true,
  },
});
// …
```

But even better, we can make the constructor functions themselves extend each other, as classes' `extends` do.

```js
function ParentWithStatic() {}

ParentWithStatic.startPosition = { x: 0, y: 0 }; // Static member property
ParentWithStatic.getStartPosition = function () {
  return this.startPosition;
};

function Child(x, y) {
  this.position = { x, y };
}

// Properly create inheritance!
Object.setPrototypeOf(Child.prototype, ParentWithStatic.prototype);
Object.setPrototypeOf(Child, ParentWithStatic);

Child.prototype.getOffsetByInitialPosition = function () {
  const position = this.position;
  const startPosition = this.constructor.getStartPosition();

  return {
    offsetX: startPosition.x - position.x,
    offsetY: startPosition.y - position.y,
  };
};

console.log(new Child(1, 1).getOffsetByInitialPosition()); // { offsetX: -1, offsetY: -1 }
```

Again, using `Object.setPrototypeOf()` may have adverse performance effects, so make sure it happens immediately after the constructor declaration and before any instances are created — to avoid objects being "tainted".

**Note:** Manually updating or setting the constructor can lead to different and sometimes confusing consequences. To prevent this, just define the role of `constructor` in each specific case. In most cases, `constructor` is not used and reassigning it is not necessary.

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

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

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

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

See also
--------

* `class`
* `constructor`
* Constructor


Object.is() - JavaScript

Object.is()
===========

The **`Object.is()`** static method determines whether two values are the same value.

Try it
------

Syntax
------

```js
Object.is(value1, value2)
```

### Parameters

`value1`

The first value to compare.

`value2`

The second value to compare.

### Return value

A boolean indicating whether or not the two arguments are the same value.

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

`Object.is()` determines whether two values are the same value. Two values are the same if one of the following holds:

* both `undefined`
* both `null`
* both `true` or both `false`
* both strings of the same length with the same characters in the same order
* both the same object (meaning both values reference the same object in memory)
* both BigInts with the same numeric value
* both symbols that reference the same symbol value
* both numbers and
    + both `+0`
    + both `-0`
    + both `NaN`
    + or both non-zero, not `NaN`, and have the same value

`Object.is()` is not equivalent to the `==` operator. The `==` operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as `"" == false` being `true`), but `Object.is()` doesn't coerce either value.

`Object.is()` is also *not* equivalent to the `===` operator. The only difference between `Object.is()` and `===` is in their treatment of signed zeros and `NaN` values. The `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal, but treats `NaN` as not equal to each other.

Examples
--------

### Using Object.is()

```js
// Case 1: Evaluation result is the same as using ===
Object.is(25, 25); // true
Object.is("foo", "foo"); // true
Object.is("foo", "bar"); // false
Object.is(null, null); // true
Object.is(undefined, undefined); // true
Object.is(window, window); // true
Object.is([], []); // false
const foo = { a: 1 };
const bar = { a: 1 };
const sameFoo = foo;
Object.is(foo, foo); // true
Object.is(foo, bar); // false
Object.is(foo, sameFoo); // true

// Case 2: Signed zero
Object.is(0, -0); // false
Object.is(+0, -0); // false
Object.is(-0, -0); // true

// Case 3: NaN
Object.is(NaN, 0 / 0); // true
Object.is(NaN, Number.NaN); // true
```

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

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

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

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

See also
--------

* Polyfill of `Object.is` in `core-js`
* Equality comparisons and sameness


Object.isFrozen() - JavaScript

Object.isFrozen()
=================

 The **`Object.isFrozen()`** static method determines if an object is
 frozen.

Try it
------

Syntax
------

```js
Object.isFrozen(obj)
```

### Parameters

`obj`

The object which should be checked.

### Return value

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

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

 An object is frozen if and only if it is not extensible, all its properties are non-configurable, and all its data
 properties (that is, properties which are not accessor properties with getter or setter
 components) are non-writable.

Examples
--------

### Using Object.isFrozen

```js
// A new object is extensible, so it is not frozen.
Object.isFrozen({}); // false

// An empty object which is not extensible
// is vacuously frozen.
const vacuouslyFrozen = Object.preventExtensions({});
Object.isFrozen(vacuouslyFrozen); // true

// A new object with one property is also extensible,
// ergo not frozen.
const oneProp = { p: 42 };
Object.isFrozen(oneProp); // false

// Preventing extensions to the object still doesn't
// make it frozen, because the property is still
// configurable (and writable).
Object.preventExtensions(oneProp);
Object.isFrozen(oneProp); // false

// Deleting that property makes the object vacuously frozen.
delete oneProp.p;
Object.isFrozen(oneProp); // true

// A non-extensible object with a non-writable
// but still configurable property is not frozen.
const nonWritable = { e: "plep" };
Object.preventExtensions(nonWritable);
Object.defineProperty(nonWritable, "e", {
  writable: false,
}); // make non-writable
Object.isFrozen(nonWritable); // false

// Changing that property to non-configurable
// then makes the object frozen.
Object.defineProperty(nonWritable, "e", {
  configurable: false,
}); // make non-configurable
Object.isFrozen(nonWritable); // true

// A non-extensible object with a non-configurable
// but still writable property also isn't frozen.
const nonConfigurable = { release: "the kraken!" };
Object.preventExtensions(nonConfigurable);
Object.defineProperty(nonConfigurable, "release", {
  configurable: false,
});
Object.isFrozen(nonConfigurable); // false

// Changing that property to non-writable
// then makes the object frozen.
Object.defineProperty(nonConfigurable, "release", {
  writable: false,
});
Object.isFrozen(nonConfigurable); // true

// A non-extensible object with a configurable
// accessor property isn't frozen.
const accessor = {
  get food() {
    return "yum";
  },
};
Object.preventExtensions(accessor);
Object.isFrozen(accessor); // false

// When we make that property non-configurable it becomes frozen.
Object.defineProperty(accessor, "food", {
  configurable: false,
});
Object.isFrozen(accessor); // true

// But the easiest way for an object to be frozen
// is if Object.freeze has been called on it.
const frozen = { 1: 81 };
Object.isFrozen(frozen); // false
Object.freeze(frozen);
Object.isFrozen(frozen); // true

// By definition, a frozen object is non-extensible.
Object.isExtensible(frozen); // false

// Also by definition, a frozen object is sealed.
Object.isSealed(frozen); // true
```

### 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.isFrozen(1);
// TypeError: 1 is not an object (ES5 code)

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

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

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

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

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

See also
--------

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


Object.prototype.toLocaleString() - JavaScript

Object.prototype.toLocaleString()
=================================

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

Try it
------

Syntax
------

```js
toLocaleString()
```

### Parameters

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

### Return value

The return value of calling `this.toString()`.

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

All objects that inherit from `Object.prototype` (that is, all except `null`-prototype objects) inherit the `toLocaleString()` method. `Object`'s `toLocaleString` returns the result of calling `this.toString()`.

This function is provided to give objects a generic `toLocaleString` method, even though not all may use it. In the core language, these built-in objects override `toLocaleString` to provide locale-specific formatting:

* `Array`: `Array.prototype.toLocaleString()`
* `Number`: `Number.prototype.toLocaleString()`
* `Date`: `Date.prototype.toLocaleString()`
* `TypedArray`: `TypedArray.prototype.toLocaleString()`
* `BigInt`: `BigInt.prototype.toLocaleString()`
Examples
--------

### Using the base toLocaleString() method

The base `toLocaleString()` method simply calls `toString()`.

```js
const obj = {
  toString() {
    return "My Object";
  },
};
console.log(obj.toLocaleString()); // "My Object"
```

### Array toLocaleString() override

`Array.prototype.toLocaleString()` is used to print array values as a string by invoking each element's `toLocaleString()` method and joining the results with a locale-specific separator. For example:

```js
const testArray = [4, 7, 10];

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

### Date toLocaleString() override

`Date.prototype.toLocaleString()` is used to print out date displays more suitable for specific locales. For example:

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

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

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

### Number toLocaleString() override

`Number.prototype.toLocaleString()` is used to print out number displays more suitable for specific locales, e.g. with the correct separators. For example:

```js
const testNumber = 2901234564;
// "2901234564"

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

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

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

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

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

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

See also
--------

* `Object.prototype.toString()`


Object.prototype.isPrototypeOf() - JavaScript

Object.prototype.isPrototypeOf()
================================

The **`isPrototypeOf()`** method of `Object` instances checks if this object exists in another object's prototype chain.

**Note:** `isPrototypeOf()` differs from the `instanceof` operator. In the expression `object instanceof AFunction`, `object`'s prototype chain is checked against `AFunction.prototype`, not against `AFunction` itself.

Try it
------

Syntax
------

```js
isPrototypeOf(object)
```

### Parameters

`object`

The object whose prototype chain will be searched.

### Return value

A boolean indicating whether the calling object (`this`) lies in the prototype chain of `object`. Directly returns `false` when `object` is not an object (i.e. a primitive).

### Exceptions

`TypeError`

Thrown if `this` is `null` or `undefined` (because it can't be converted to an object).

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

All objects that inherit from `Object.prototype` (that is, all except `null`-prototype objects) inherit the `isPrototypeOf()` method. This method allows you to check whether or not the object exists within another object's prototype chain. If the `object` passed as the parameter is not an object (i.e. a primitive), the method directly returns `false`. Otherwise, the `this` value is converted to an object, and the prototype chain of `object` is searched for the `this` value, until the end of the chain is reached or the `this` value is found.

Examples
--------

### Using isPrototypeOf()

This example demonstrates that `Baz.prototype`, `Bar.prototype`, `Foo.prototype` and `Object.prototype` exist in the prototype chain for object `baz`:

```js
class Foo {}
class Bar extends Foo {}
class Baz extends Bar {}

const foo = new Foo();
const bar = new Bar();
const baz = new Baz();

// prototype chains:
// foo: Foo --> Object
// bar: Bar --> Foo --> Object
// baz: Baz --> Bar --> Foo --> Object
console.log(Baz.prototype.isPrototypeOf(baz)); // true
console.log(Baz.prototype.isPrototypeOf(bar)); // false
console.log(Baz.prototype.isPrototypeOf(foo)); // false
console.log(Bar.prototype.isPrototypeOf(baz)); // true
console.log(Bar.prototype.isPrototypeOf(foo)); // false
console.log(Foo.prototype.isPrototypeOf(baz)); // true
console.log(Foo.prototype.isPrototypeOf(bar)); // true
console.log(Object.prototype.isPrototypeOf(baz)); // true
```

The `isPrototypeOf()` method — along with the `instanceof` operator — comes in particularly handy if you have code that can only function when dealing with objects descended from a specific prototype chain; e.g., to guarantee that certain methods or properties will be present on that object.

For example, to execute some code that's only safe to run if a `baz` object has `Foo.prototype` in its prototype chain, you can do this:

```js
if (Foo.prototype.isPrototypeOf(baz)) {
  // do something safe
}
```

However, `Foo.prototype` existing in `baz`'s prototype chain doesn't imply `baz` was created using `Foo` as its constructor. For example, `baz` could be directly assigned with `Foo.prototype` as its prototype. In this case, if your code reads private fields of `Foo` from `baz`, it would still fail:

```js
class Foo {
  #value = "foo";
  static getValue(x) {
    return x.#value;
  }
}

const baz = { \_\_proto\_\_: Foo.prototype };

if (Foo.prototype.isPrototypeOf(baz)) {
  console.log(Foo.getValue(baz)); // TypeError: Cannot read private member #value from an object whose class did not declare it
}
```

The same applies to `instanceof`. If you need to read private fields in a secure way, offer a branded check method using `in` instead.

```js
class Foo {
  #value = "foo";
  static getValue(x) {
    return x.#value;
  }
  static isFoo(x) {
    return #value in x;
  }
}

const baz = { \_\_proto\_\_: Foo.prototype };

if (Foo.isFoo(baz)) {
  // Doesn't run, because baz is not a Foo
  console.log(Foo.getValue(baz));
}
```

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

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

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

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

See also
--------

* `instanceof`
* `Object.getPrototypeOf()`
* `Object.setPrototypeOf()`
* Inheritance and the prototype chain