Symbol.prototype.toString() - JavaScript

Symbol.prototype.toString()
===========================

The **`toString()`** method of `Symbol` values returns a string representing this symbol value.

Try it
------

Syntax
------

```js
toString()
```

### Parameters

None.

### Return value

A string representing the specified symbol value.

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

 The `Symbol` object overrides the `toString` method of `Object`; it does not inherit
 `Object.prototype.toString()`. For `Symbol` values, the `toString` method returns a descriptive string in the form `"Symbol(description)"`, where `description` is the symbol's description.

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

Because `Symbol` has a `[@@toPrimitive]()` method, that method always takes priority over `toString()` when a `Symbol` object is coerced to a string. However, because `Symbol.prototype[@@toPrimitive]()` returns a symbol primitive, and symbol primitives throw a `TypeError` when implicitly converted to a string, the `toString()` method is never implicitly called by the language. To stringify a symbol, you must explicitly call its `toString()` method or use the `String()` function.

Examples
--------

### Using toString()

```js
Symbol("desc").toString(); // "Symbol(desc)"

// well-known symbols
Symbol.iterator.toString(); // "Symbol(Symbol.iterator)"

// global symbols
Symbol.for("foo").toString(); // "Symbol(foo)"
```

### Implicitly calling toString()

The only way to make JavaScript implicitly call `toString()` instead of `[@@toPrimitive]()` on a symbol wrapper object is by deleting the `@@toPrimitive` method first.

**Warning:** You should not do this in practice. Never mutate built-in objects unless you know exactly what you're doing.

```js
delete Symbol.prototype[Symbol.toPrimitive];
console.log(`${Object(Symbol("foo"))}`); // "Symbol(foo)"
```

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

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

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

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

See also
--------

* `Object.prototype.toString()`


Symbol.match - JavaScript

Symbol.match
============

The **`Symbol.match`** static data property represents the well-known symbol `@@match`. The `String.prototype.match()` method looks up this symbol on its first argument for the method used to match an input string against the current object. This symbol is also used to determine if an object should be treated as a regex.

For more information, see `RegExp.prototype[@@match]()` and `String.prototype.match()`.

Try it
------

Value
-----

The well-known symbol `@@match`.

| Property attributes of `Symbol.match` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

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

This function is also used to identify if objects have the behavior of regular expressions. For example, the methods `String.prototype.startsWith()`, `String.prototype.endsWith()` and `String.prototype.includes()`, check if their first argument is a regular expression and will throw a `TypeError` if they are. Now, if the `match` symbol is set to `false` (or a Falsy value except `undefined`), it indicates that the object is not intended to be used as a regular expression object.

Examples
--------

### Marking a RegExp as not a regex

The following code will throw a `TypeError`:

```js
"/bar/".startsWith(/bar/);

// Throws TypeError, as /bar/ is a regular expression
// and Symbol.match is not modified.
```

However, if you set `Symbol.match` to `false`, the object will be considered as not a regular expression object. The methods `startsWith` and `endsWith` won't throw a `TypeError` as a consequence.

```js
const re = /foo/;
re[Symbol.match] = false;
"/foo/".startsWith(re); // true
"/baz/".endsWith(re); // false
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.match |

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

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

See also
--------

* Polyfill of `Symbol.match` in `core-js`
* `Symbol.matchAll`
* `Symbol.replace`
* `Symbol.search`
* `Symbol.split`
* `String.prototype.match()`
* `RegExp.prototype[@@match]()`


Symbol.prototype.valueOf() - JavaScript

Symbol.prototype.valueOf()
==========================

The **`valueOf()`** method of `Symbol` values returns this symbol value.

Try it
------

Syntax
------

```js
valueOf()
```

### Parameters

None.

### Return value

The primitive value of the specified `Symbol` object.

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

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

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

Examples
--------

### Using valueOf()

```js
const sym = Symbol("example");
sym === sym.valueOf(); // true
```

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

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

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

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

See also
--------

* `Object.prototype.valueOf()`


Symbol.matchAll - JavaScript

Symbol.matchAll
===============

The **`Symbol.matchAll`** static data property represents the well-known symbol `@@matchAll`. The `String.prototype.matchAll()` method looks up this symbol on its first argument for the method that returns an iterator, that yields matches of the current object against a string.

For more information, see `RegExp.prototype[@@matchAll]()` and `String.prototype.matchAll()`.

Try it
------

Value
-----

The well-known symbol `@@matchAll`.

| Property attributes of `Symbol.matchAll` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

Examples
--------

### Using Symbol.matchAll

```js
const str = "2016-01-02|2019-03-07";

const numbers = {
  \*[Symbol.matchAll](str) {
    for (const n of str.matchAll(/[0-9]+/g)) yield n[0];
  },
};

console.log(Array.from(str.matchAll(numbers)));
// ["2016", "01", "02", "2019", "03", "07"]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.matchall |

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

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

See also
--------

* Polyfill of `Symbol.matchAll` in `core-js`
* `Symbol.match`
* `Symbol.replace`
* `Symbol.search`
* `Symbol.split`
* `String.prototype.matchAll()`
* `RegExp.prototype[@@matchAll]()`


Symbol.iterator - JavaScript

Symbol.iterator
===============

The **`Symbol.iterator`** static data property represents the well-known symbol `@@iterator`. The iterable protocol looks up this symbol for the method that returns the iterator for an object. In order for an object to be iterable, it must have an `@@iterator` key.

Try it
------

Value
-----

The well-known symbol `@@iterator`.

| Property attributes of `Symbol.iterator` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

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

Whenever an object needs to be iterated (such as at the beginning of a `for...of` loop), its `@@iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated.

Some built-in types have a default iteration behavior, while other types (such as `Object`) do not. Some built-in types with a `@@iterator` method are:

* `Array.prototype[@@iterator]()`
* `TypedArray.prototype[@@iterator]()`
* `String.prototype[@@iterator]()`
* `Map.prototype[@@iterator]()`
* `Set.prototype[@@iterator]()`

See also Iteration protocols for more information.

Examples
--------

### User-defined iterables

We can make our own iterables like this:

```js
const myIterable = {};
myIterable[Symbol.iterator] = function\* () {
  yield 1;
  yield 2;
  yield 3;
};
[...myIterable]; // [1, 2, 3]
```

Or iterables can be defined directly inside a class or object using a computed property:

```js
class Foo {
  \*[Symbol.iterator]() {
    yield 1;
    yield 2;
    yield 3;
  }
}

const someObj = {
  \*[Symbol.iterator]() {
    yield "a";
    yield "b";
  },
};

console.log(...new Foo()); // 1, 2, 3
console.log(...someObj); // 'a', 'b'
```

### Non-well-formed iterables

If an iterable's `@@iterator` method does not return an iterator object, then it is a non-well-formed iterable. Using it as such is likely to result in runtime exceptions or buggy behavior:

```js
const nonWellFormedIterable = {};
nonWellFormedIterable[Symbol.iterator] = () => 1;
[...nonWellFormedIterable]; // TypeError: [Symbol.iterator]() returned a non-object value
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.iterator |

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

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

See also
--------

* Polyfill of `Symbol.iterator` in `core-js`
* Iteration protocols
* `Array.prototype[@@iterator]()`
* `TypedArray.prototype[@@iterator]()`
* `String.prototype[@@iterator]()`
* `Map.prototype[@@iterator]()`
* `Set.prototype[@@iterator]()`
* `arguments[@@iterator]()`
* `Segments.prototype[@@iterator]()`


Symbol.replace - JavaScript

Symbol.replace
==============

The **`Symbol.replace`** static data property represents the well-known symbol `@@replace`. The `String.prototype.replace()` method looks up this symbol on its first argument for the method that replaces substrings matched by the current object.

For more information, see `RegExp.prototype[@@replace]()` and `String.prototype.replace()`.

Try it
------

Value
-----

The well-known symbol `@@replace`.

| Property attributes of `Symbol.replace` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

Examples
--------

### Using Symbol.replace

```js
class CustomReplacer {
  constructor(value) {
    this.value = value;
  }
  [Symbol.replace](string) {
    return string.replace(this.value, "#!@?");
  }
}

console.log("football".replace(new CustomReplacer("foo"))); // "#!@?tball"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.replace |

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

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

See also
--------

* Polyfill of `Symbol.replace` in `core-js`
* `Symbol.match`
* `Symbol.matchAll`
* `Symbol.search`
* `Symbol.split`
* `String.prototype.replace()`
* `RegExp.prototype[@@replace]()`


AsyncGeneratorFunction() constructor - JavaScript

AsyncGeneratorFunction() constructor
====================================

The **`AsyncGeneratorFunction()`** constructor creates `AsyncGeneratorFunction` objects.

Note that `AsyncGeneratorFunction` is not a global object. It could be obtained by evaluating the following code.

```js
const AsyncGeneratorFunction = async function\* () {}.constructor;
```

The `AsyncGeneratorFunction()` constructor is not intended to be used directly, and all caveats mentioned in the `Function()` description apply to `AsyncGeneratorFunction()`.

Syntax
------

```js
new AsyncGeneratorFunction(functionBody)
new AsyncGeneratorFunction(arg1, functionBody)
new AsyncGeneratorFunction(arg1, arg2, functionBody)
new AsyncGeneratorFunction(arg1, arg2, /\* …, \*/ argN, functionBody)

AsyncGeneratorFunction(functionBody)
AsyncGeneratorFunction(arg1, functionBody)
AsyncGeneratorFunction(arg1, arg2, functionBody)
AsyncGeneratorFunction(arg1, arg2, /\* …, \*/ argN, functionBody)
```

**Note:** `AsyncGeneratorFunction()` can be called with or without `new`. Both create a new `AsyncGeneratorFunction` instance.

### Parameters

See `Function()`.

Examples
--------

### Using the constructor

The following example uses the `AsyncGeneratorFunction` constructor to create an async generator function.

```js
const AsyncGeneratorFunction = async function\* () {}.constructor;
const createAsyncGenerator = new AsyncGeneratorFunction("a", "yield a \* 2");
const asyncGen = createAsyncGenerator(10);
asyncGen.next().then((res) => console.log(res.value)); // 20
```

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

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

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

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

See also
--------

* `async function*`
* `async function*` expression
* `Function()` constructor
* Iterators and generators guide
* Functions


ArrayBuffer.prototype.transferToFixedLength() - JavaScript

ArrayBuffer.prototype.transferToFixedLength()
=============================================

The **`transferToFixedLength()`** method of `ArrayBuffer` instances creates a new non-resizable `ArrayBuffer` with the same byte content as this buffer, then detaches this buffer.

Syntax
------

```js
transferToFixedLength()
transferToFixedLength(newByteLength)
```

### Parameters

`newByteLength`

The `byteLength` of the new `ArrayBuffer`. Defaults to the `byteLength` of this `ArrayBuffer`.

* If `newByteLength` is smaller than the `byteLength` of this `ArrayBuffer`, the "overflowing" bytes are dropped.
* If `newByteLength` is larger than the `byteLength` of this `ArrayBuffer`, the extra bytes are filled with zeros.

### Return value

A new `ArrayBuffer` object. Its contents are initialized to the contents of this `ArrayBuffer`, and extra bytes, if any, are filled with zeros. The new `ArrayBuffer` is always non-resizable. The original `ArrayBuffer` is detached.

### Exceptions

`TypeError`

Thrown if this `ArrayBuffer` is already detached.

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

Unlike `transfer()`, `transferToFixedLength()` always creates a non-resizable `ArrayBuffer`. This means `newByteLength` can be larger than the `maxByteLength`, even if this `ArrayBuffer` is resizable. See transferring ArrayBuffers for more information.

Examples
--------

### Transferring a resizable ArrayBuffer to fixed-length

```js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
const view = new Uint8Array(buffer);
view[1] = 2;
view[7] = 4;

const buffer2 = buffer.transferToFixedLength();
console.log(buffer2.byteLength); // 8
console.log(buffer2.resizable); // false
const view2 = new Uint8Array(buffer2);
console.log(view2[1]); // 2
console.log(view2[7]); // 4
```

Using `transferToFixedLength`, `newByteLength` can be larger than the `maxByteLength` of the original `ArrayBuffer`.

```js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
const view = new Uint8Array(buffer);
view[1] = 2;
view[7] = 4;

const buffer2 = buffer.transferToFixedLength(20);
console.log(buffer2.byteLength); // 20
console.log(buffer2.resizable); // false
const view2 = new Uint8Array(buffer2);
console.log(view2[1]); // 2
console.log(view2[7]); // 4
```

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

| Specification |
| --- |
| ArrayBuffer transfer # sec-arraybuffer.prototype.transfertofixedlength |

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

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

See also
--------

* Polyfill of `ArrayBuffer.prototype.transferToFixedLength()` in `core-js`
* `ArrayBuffer`
* `ArrayBuffer.prototype.detached`
* `ArrayBuffer.prototype.transfer()`


ArrayBuffer.prototype.maxByteLength - JavaScript

ArrayBuffer.prototype.maxByteLength
===================================

The **`maxByteLength`** accessor property of `ArrayBuffer` instances returns the maximum length (in bytes) that this array buffer can be resized to.

Try it
------

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

The `maxByteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed, set via the `maxByteLength` option of the `ArrayBuffer()` constructor, and cannot be changed.

This property returns 0 if this `ArrayBuffer` has been detached. If this `ArrayBuffer` was constructed without specifying a `maxByteLength` value, this property returns a value equal to the value of the `ArrayBuffer`'s `byteLength`.

Examples
--------

### Using maxByteLength

In this example, we create an 8-byte buffer that is resizable to a max length of 16 bytes, then return its `maxByteLength`:

```js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });

buffer.maxByteLength; // 16
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-arraybuffer.prototype.maxbytelength |

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

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

See also
--------

* `ArrayBuffer`
* `ArrayBuffer.prototype.byteLength`
* `ArrayBuffer.prototype.resize()`


ArrayBuffer.prototype.byteLength - JavaScript

ArrayBuffer.prototype.byteLength
================================

The **`byteLength`** accessor property of `ArrayBuffer` instances returns the length (in bytes) of this array buffer.

Try it
------

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

The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed and cannot be changed. This property returns 0 if this `ArrayBuffer` has been detached.

Examples
--------

### Using byteLength

```js
const buffer = new ArrayBuffer(8);
buffer.byteLength; // 8
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-arraybuffer.prototype.bytelength |

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

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

See also
--------

* `ArrayBuffer`


ArrayBuffer.prototype.resizable - JavaScript

ArrayBuffer.prototype.resizable
===============================

The **`resizable`** accessor property of `ArrayBuffer` instances returns whether this array buffer can be resized or not.

Try it
------

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

The `resizable` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed. If the `maxByteLength` option was set in the constructor, `resizable` will return `true`; if not, it will return `false`.

Examples
--------

### Using resizable

In this example, we create a 8-byte buffer that is resizable to a max length of 16 bytes, then check its `resizable` property, resizing it if `resizable` returns `true`:

```js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });

if (buffer.resizable) {
  console.log("Buffer is resizable!");
  buffer.resize(12);
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-arraybuffer.prototype.resizable |

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

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

See also
--------

* `ArrayBuffer`
* `ArrayBuffer.prototype.maxByteLength`
* `ArrayBuffer.prototype.resize()`


ArrayBuffer.prototype.transfer() - JavaScript

ArrayBuffer.prototype.transfer()
================================

The **`transfer()`** method of `ArrayBuffer` instances creates a new `ArrayBuffer` with the same byte content as this buffer, then detaches this buffer.

Syntax
------

```js
transfer()
transfer(newByteLength)
```

### Parameters

`newByteLength` Optional

The `byteLength` of the new `ArrayBuffer`. Defaults to the `byteLength` of this `ArrayBuffer`.

* If `newByteLength` is smaller than the `byteLength` of this `ArrayBuffer`, the "overflowing" bytes are dropped.
* If `newByteLength` is larger than the `byteLength` of this `ArrayBuffer`, the extra bytes are filled with zeros.
* If this `ArrayBuffer` is resizable, `newByteLength` must not be greater than its `maxByteLength`.

### Return value

A new `ArrayBuffer` object. Its contents are initialized to the contents of this `ArrayBuffer`, and extra bytes, if any, are filled with zeros. The new `ArrayBuffer` is resizable if and only if this `ArrayBuffer` is resizable, in which case its `maxByteLength` is the same as this `ArrayBuffer`'s. The original `ArrayBuffer` is detached.

### Exceptions

`RangeError`

Thrown if this `ArrayBuffer` is resizable and `newByteLength` is greater than the `maxByteLength` of this `ArrayBuffer`.

`TypeError`

Thrown if this `ArrayBuffer` is already detached.

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

The `transfer()` method performs the same operation as the structured clone algorithm. It copies the bytes of this `ArrayBuffer` into a new `ArrayBuffer` object, then detaches this `ArrayBuffer` object. See transferring ArrayBuffers for more information.

`transfer()` preserves the resizability of this `ArrayBuffer`. If you want the new `ArrayBuffer` to be non-resizable, use `transferToFixedLength()` instead. There's no way to transfer a buffer that makes a fixed-length buffer become resizable.

`transfer()` is very efficient because implementations may implement this method as a zero-copy move or a `realloc` — there does not need to be an actual copy of the data.

Examples
--------

### Transferring an ArrayBuffer

```js
// Create an ArrayBuffer and write a few bytes
const buffer = new ArrayBuffer(8);
const view = new Uint8Array(buffer);
view[1] = 2;
view[7] = 4;

// Copy the buffer to the same size
const buffer2 = buffer.transfer();
console.log(buffer.detached); // true
console.log(buffer2.byteLength); // 8
const view2 = new Uint8Array(buffer2);
console.log(view2[1]); // 2
console.log(view2[7]); // 4

// Copy the buffer to a smaller size
const buffer3 = buffer2.transfer(4);
console.log(buffer3.byteLength); // 4
const view3 = new Uint8Array(buffer3);
console.log(view3[1]); // 2
console.log(view3[7]); // undefined

// Copy the buffer to a larger size
const buffer4 = buffer3.transfer(8);
console.log(buffer4.byteLength); // 8
const view4 = new Uint8Array(buffer4);
console.log(view4[1]); // 2
console.log(view4[7]); // 0

// Already detached, throws TypeError
buffer.transfer(); // TypeError: Cannot perform ArrayBuffer.prototype.transfer on a detached ArrayBuffer
```

### Transferring a resizable ArrayBuffer

```js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
const view = new Uint8Array(buffer);
view[1] = 2;
view[7] = 4;

// Copy the buffer to a smaller size
const buffer2 = buffer.transfer(4);
console.log(buffer2.byteLength); // 4
console.log(buffer2.maxByteLength); // 16
const view2 = new Uint8Array(buffer2);
console.log(view2[1]); // 2
console.log(view2[7]); // undefined
buffer2.resize(8);
console.log(view2[7]); // 0

// Copy the buffer to a larger size within maxByteLength
const buffer3 = buffer2.transfer(12);
console.log(buffer3.byteLength); // 12

// Copy the buffer to a larger size than maxByteLength
buffer3.transfer(20); // RangeError: Invalid array buffer length
```

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

| Specification |
| --- |
| ArrayBuffer transfer # sec-arraybuffer.prototype.transfer |

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

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

See also
--------

* Polyfill of `ArrayBuffer.prototype.transfer()` in `core-js`
* `ArrayBuffer`
* `ArrayBuffer.prototype.detached`
* `ArrayBuffer.prototype.transferToFixedLength()`


ArrayBuffer.isView() - JavaScript

ArrayBuffer.isView()
====================

 The **`ArrayBuffer.isView()`** static method determines whether the
 passed value is one of the `ArrayBuffer` views,
 such as typed array objects
 or a `DataView`.

Try it
------

Syntax
------

```js
ArrayBuffer.isView(value)
```

### Parameters

`value`

The value to be checked.

### Return value

`true` if the given argument is one of the `ArrayBuffer` views;
 otherwise, `false`.

Examples
--------

### Using isView

```js
ArrayBuffer.isView(); // false
ArrayBuffer.isView([]); // false
ArrayBuffer.isView({}); // false
ArrayBuffer.isView(null); // false
ArrayBuffer.isView(undefined); // false
ArrayBuffer.isView(new ArrayBuffer(10)); // false

ArrayBuffer.isView(new Uint8Array()); // true
ArrayBuffer.isView(new Float32Array()); // true
ArrayBuffer.isView(new Int8Array(10).subarray(0, 3)); // true

const buffer = new ArrayBuffer(2);
const dv = new DataView(buffer);
ArrayBuffer.isView(dv); // true
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-arraybuffer.isview |

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

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

See also
--------

* JavaScript typed arrays guide


ArrayBuffer[@@species] - JavaScript

ArrayBuffer[@@species]
======================

The **`ArrayBuffer[@@species]`** static accessor property returns the constructor used to construct return values from array buffer methods.

**Warning:** The existence of `@@species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are investigating whether to remove this feature. Avoid relying on it if possible.

Syntax
------

```js
ArrayBuffer[Symbol.species]
```

### Return value

The value of the constructor (`this`) on which `get @@species` was called. The return value is used to construct return values from array buffer methods that create new array buffers.

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

The `@@species` accessor property returns the default constructor for `ArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:

```js
// Hypothetical underlying implementation for illustration
class ArrayBuffer {
  static get [Symbol.species]() {
    return this;
  }
}
```

Because of this polymorphic implementation, `@@species` of derived subclasses would also return the constructor itself by default.

```js
class SubArrayBuffer extends ArrayBuffer {}
SubArrayBuffer[Symbol.species] === SubArrayBuffer; // true
```

When calling array buffer methods that do not mutate the existing object but return a new array buffer instance (for example, `slice()`), the object's `constructor[@@species]` will be accessed. The returned constructor will be used to construct the return value of the array buffer method.

Examples
--------

### Species in ordinary objects

The `@@species` property returns the default constructor function, which is the `ArrayBuffer` constructor for `ArrayBuffer`.

```js
ArrayBuffer[Symbol.species]; // function ArrayBuffer()
```

### Species in derived objects

In an instance of a custom `ArrayBuffer` subclass, such as `MyArrayBuffer`, the `MyArrayBuffer` species is the `MyArrayBuffer` constructor. However, you might want to overwrite this, in order to return parent `ArrayBuffer` objects in your derived class methods:

```js
class MyArrayBuffer extends ArrayBuffer {
  // Overwrite MyArrayBuffer species to the parent ArrayBuffer constructor
  static get [Symbol.species]() {
    return ArrayBuffer;
  }
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-arraybuffer-@@species |

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

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

See also
--------

* `ArrayBuffer`
* `Symbol.species`


ArrayBuffer.prototype.slice() - JavaScript

ArrayBuffer.prototype.slice()
=============================

The **`slice()`** method of `ArrayBuffer` instances returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `start`, inclusive, up to `end`, exclusive. If either `start` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning.

Try it
------

Syntax
------

```js
slice()
slice(start)
slice(start, end)
```

### Parameters

`start` Optional

Zero-based index at which to start extraction, converted to an integer.

* Negative index counts back from the end of the buffer — if `start < 0`, `start + buffer.length` is used.
* If `start < -buffer.length` or `start` is omitted, `0` is used.
* If `start >= buffer.length`, nothing is extracted.

`end` Optional

Zero-based index at which to end extraction, converted to an integer. `slice()` extracts up to but not including `end`.

* Negative index counts back from the end of the buffer — if `end < 0`, `end + buffer.length` is used.
* If `end < -buffer.length`, `0` is used.
* If `end >= buffer.length` or `end` is omitted, `buffer.length` is used, causing all elements until the end to be extracted.
* If `end` is positioned before or at `start` after normalization, nothing is extracted.

### Return value

A new `ArrayBuffer` containing the extracted elements.

Examples
--------

### Copying an ArrayBuffer

```js
const buf1 = new ArrayBuffer(8);
const buf2 = buf1.slice(0);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-arraybuffer.prototype.slice |

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

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

See also
--------

* `ArrayBuffer`
* `SharedArrayBuffer.prototype.slice()`


ArrayBuffer.prototype.detached - JavaScript

ArrayBuffer.prototype.detached
==============================

The **`detached`** accessor property of `ArrayBuffer` instances returns a boolean indicating whether or not this buffer has been detached (transferred).

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

The `detached` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is `false` when the `ArrayBuffer` is first created. The value becomes `true` if the `ArrayBuffer` is transferred, which detaches the instance from its underlying memory. Once a buffer becomes detached, it is no longer usable.

Examples
--------

### Using detached

```js
const buffer = new ArrayBuffer(8);
console.log(buffer.detached); // false
const newBuffer = buffer.transfer();
console.log(buffer.detached); // true
console.log(newBuffer.detached); // false
```

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

| Specification |
| --- |
| ArrayBuffer transfer # sec-get-arraybuffer.prototype.detached |

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

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

See also
--------

* Polyfill of `ArrayBuffer.prototype.detached` in `core-js`
* `ArrayBuffer`
* `ArrayBuffer.prototype.transfer()`
* `ArrayBuffer.prototype.transferToFixedLength()`


ArrayBuffer.prototype.resize() - JavaScript

ArrayBuffer.prototype.resize()
==============================

The **`resize()`** method of `ArrayBuffer` instances resizes the `ArrayBuffer` to the specified size, in bytes.

Try it
------

Syntax
------

```js
resize(newLength)
```

### Parameters

`newLength`

The new length, in bytes, to resize the `ArrayBuffer` to.

### Return value

None (`undefined`).

### Exceptions

`TypeError`

Thrown if the `ArrayBuffer` is detached or is not resizable.

`RangeError`

Thrown if `newLength` is larger than the `maxByteLength` of the `ArrayBuffer`.

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

The `resize()` method resizes an `ArrayBuffer` to the size specified by the `newLength` parameter, provided that the `ArrayBuffer` is resizable and the new size is less than or equal to the `maxByteLength` of the `ArrayBuffer`. New bytes are initialized to 0.

Note that you can use `resize()` to shrink as well as grow an `ArrayBuffer` — it is permissible for `newLength` to be smaller than the `ArrayBuffer`'s current `byteLength`.

Examples
--------

### Using resize()

In this example, we create a 8-byte buffer that is resizable to a max length of 16 bytes, then check its `resizable` property, resizing it if `resizable` returns `true`:

```js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });

if (buffer.resizable) {
  console.log("Buffer is resizable!");
  buffer.resize(12);
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-arraybuffer.prototype.resize |

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

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

See also
--------

* `ArrayBuffer`
* `ArrayBuffer.prototype.resizable`
* `ArrayBuffer.prototype.maxByteLength`


ArrayBuffer() constructor - JavaScript

ArrayBuffer() constructor
=========================

The **`ArrayBuffer()`** constructor creates `ArrayBuffer` objects.

Try it
------

Syntax
------

```js
new ArrayBuffer(length)
new ArrayBuffer(length, options)
```

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

### Parameters

`length`

The size, in bytes, of the array buffer to create.

`options` Optional

An object, which can contain the following properties:

`maxByteLength` Optional

The maximum size, in bytes, that the array buffer can be resized to.

### Return value

A new `ArrayBuffer` object of the specified size, with its `maxByteLength` property set to the specified `maxByteLength` if one was specified. Its contents are initialized to 0.

### Exceptions

`RangeError`

Thrown in one of the following cases:

* `length` or `maxByteLength` is larger than `Number.MAX_SAFE_INTEGER` (≥ 253) or negative.
* `length` is larger than `maxByteLength`.

Examples
--------

### Creating an ArrayBuffer

In this example, we create a 8-byte buffer with a `Int32Array` view referring to the buffer:

```js
const buffer = new ArrayBuffer(8);
const view = new Int32Array(buffer);
```

### Creating a resizable ArrayBuffer

In this example, we create a 8-byte buffer that is resizable to a max length of 16 bytes, then `resize()` it to 12 bytes:

```js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });

buffer.resize(12);
```

**Note:** It is recommended that `maxByteLength` is set to the smallest value possible for your use case. It should never exceed `1073741824` (1GB) to reduce the risk of out-of-memory errors.

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

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

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

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

See also
--------

* Polyfill of `ArrayBuffer` in `core-js`
* JavaScript typed arrays guide
* `SharedArrayBuffer`


Function.prototype[@@hasInstance]() - JavaScript

Function.prototype[@@hasInstance]()
===================================

The **`[@@hasInstance]()`** method of `Function` instances specifies the default procedure for determining if a constructor function recognizes an object as one of the constructor's instances. It is called by the `instanceof` operator.

Syntax
------

```js
func[Symbol.hasInstance](value)
```

### Parameters

`value`

The object to test. Primitive values always return `false`.

### Return value

`true` if `func.prototype` is in the prototype chain of `value`; otherwise, `false`. Always returns `false` if `value` is not an object or `this` is not a function. If `this` is a bound function, returns the result of a `instanceof` test on `value` and the underlying target function.

### Exceptions

`TypeError`

Thrown if `this` is not a bound function and `this.prototype` is not an object.

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

The `instanceof` operator calls the `[@@hasInstance]()` method of the right-hand side whenever such a method exists. Because all functions inherit from `Function.prototype` by default, they would all have the `[@@hasInstance]()` method, so most of the time, the `Function.prototype[@@hasInstance]` method specifies the behavior of `instanceof` when the right-hand side is a function. This method implements the default behavior of the `instanceof` operator (the same algorithm when `constructor` has no `@@hasInstance` method).

Unlike most methods, the `Function.prototype[@@hasInstance]()` property is non-configurable and non-writable. This is a security feature to prevent the underlying target function of a bound function from being obtainable. See this StackOverflow answer for an example.

Examples
--------

### Reverting to default instanceof behavior

You would rarely need to call this method directly. Instead, this method is called by the `instanceof` operator. You should expect the two results to usually be equivalent.

```js
class Foo {}
const foo = new Foo();
console.log(foo instanceof Foo === Foo[Symbol.hasInstance](foo)); // true
```

You may want to use this method if you want to invoke the default `instanceof` behavior, but you don't know if a constructor has a overridden `[@@hasInstance]()` method.

```js
class Foo {
  static [Symbol.hasInstance](value) {
    // A custom implementation
    return false;
  }
}

const foo = new Foo();
console.log(foo instanceof Foo); // false
console.log(Function.prototype[Symbol.hasInstance].call(Foo, foo)); // true
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-function.prototype-@@hasinstance |

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

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

See also
--------

* `instanceof`
* `Symbol.hasInstance`


Function.prototype.arguments - JavaScript

Function.prototype.arguments
============================

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

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

**Note:** The `arguments` property of `Function` objects is deprecated. The recommended way to access the `arguments` object is to refer to the variable `arguments` available within functions.

The **`arguments`** accessor property of `Function` instances returns the arguments passed to this function. For strict, arrow, async, and generator functions, accessing the `arguments` property throws a `TypeError`.

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

The value of `arguments` is an array-like object corresponding to the arguments passed to a function.

In the case of recursion, i.e. if function `f` appears several times on the call stack, the value of `f.arguments` represents the arguments corresponding to the most recent invocation of the function.

The value of the `arguments` property is normally `null` if there is no outstanding invocation of the function in progress (that is, the function has been called but has not yet returned).

Note that the only behavior specified by the ECMAScript specification is that `Function.prototype` has an initial `arguments` accessor that unconditionally throws a `TypeError` for any `get` or `set` request (known as a "poison pill accessor"), and that implementations are not allowed to change this semantic for any function except non-strict plain functions. The actual behavior of the `arguments` property, if it's anything other than throwing an error, is implementation-defined. For example, Chrome defines it as an own data property, while Firefox and Safari extend the initial poison-pill `Function.prototype.arguments` accessor to specially handle `this` values that are non-strict functions.

```js
(function f() {
  if (Object.hasOwn(f, "arguments")) {
    console.log(
      "arguments is an own property with descriptor",
      Object.getOwnPropertyDescriptor(f, "arguments"),
    );
  } else {
    console.log(
      "f doesn't have an own property named arguments. Trying to get f.[[Prototype]].arguments",
    );
    console.log(
      Object.getOwnPropertyDescriptor(
        Object.getPrototypeOf(f),
        "arguments",
      ).get.call(f),
    );
  }
})();

// In Chrome:
// arguments is an own property with descriptor {value: Arguments(0), writable: false, enumerable: false, configurable: false}

// In Firefox:
// f doesn't have an own property named arguments. Trying to get f.[[Prototype]].arguments
// Arguments { … }
```

Examples
--------

### Using the arguments property

```js
function f(n) {
  g(n - 1);
}

function g(n) {
  console.log(`before: ${g.arguments[0]}`);
  if (n > 0) {
    f(n);
  }
  console.log(`after: ${g.arguments[0]}`);
}

f(2);

console.log(`returned: ${g.arguments}`);

// Logs:
// before: 1
// before: 0
// after: 0
// after: 1
// returned: null
```

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

Not part of any standard.

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

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

See also
--------

* `arguments`
* Functions


Function.prototype.toString() - JavaScript

Function.prototype.toString()
=============================

The **`toString()`** method of `Function` instances returns a string representing the source code of this function.

Try it
------

Syntax
------

```js
toString()
```

### Parameters

None.

### Return value

A string representing the source code of the function.

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

 The `Function` object overrides the `toString()` method
 inherited from `Object`; it does not inherit
 `Object.prototype.toString`. For user-defined `Function`
 objects, the `toString` method returns a string containing the source text
 segment which was used to define the function.

 JavaScript calls the `toString` method automatically when a
 `Function` is to be represented as a text value, e.g. when a function is
 concatenated with a string.

 The `toString()` method will throw a `TypeError` exception
 ("Function.prototype.toString called on incompatible object"), if its
 `this` value object is not a `Function` object.

```js
Function.prototype.toString.call("foo"); // throws TypeError
```

 If the `toString()` method is called on built-in function objects, a
 function created by `Function.prototype.bind()`, or
 other non-JavaScript functions, then `toString()` returns a
 *native function string* which looks like
```

function someName() { [native code] }
```

For intrinsic object methods and functions, `someName` is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like `[1 + 1]`, `someName`, or `1`.

**Note:** This means using `eval()` on native function strings is a guaranteed syntax error.

If the `toString()` method is called on a function created by the `Function` constructor, `toString()` returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. For example, `Function("a", "b", "return a + b").toString()` will return:
```

function anonymous(a,b
) {
return a + b
}
```

Since ES2018, the spec requires the return value of `toString()` to be the exact same source code as it was declared, including any whitespace and/or comments — or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the compatibility table.

Examples
--------

### Comparing actual source code and toString results

```js
function test(fn) {
  console.log(fn.toString());
}

function f() {}
class A {
  a() {}
}
function\* g() {}

test(f); // "function f() {}"
test(A); // "class A { a() {} }"
test(g); // "function\* g() {}"
test((a) => a); // "(a) => a"
test({ a() {} }.a); // "a() {}"
test({ \*a() {} }.a); // "\*a() {}"
test({ [0]() {} }[0]); // "[0]() {}"
test(Object.getOwnPropertyDescriptor({ get a() {} }, "a").get); // "get a() {}"
test(Object.getOwnPropertyDescriptor({ set a(x) {} }, "a").set); // "set a(x) {}"
test(Function.prototype.toString); // "function toString() { [native code] }"
test(function f() {}.bind(0)); // "function () { [native code] }"
test(Function("a", "b")); // function anonymous(a\n) {\nb\n}
```

Note that after the `Function.prototype.toString()` revision, when `toString()` is called, implementations are never allowed to synthesize a function's source that is not a native function string. The method always returns the exact source code used to create the function — including the getter and setter examples above. The `Function` constructor itself has the capability of synthesizing the source code for the function (and is therefore a form of implicit `eval()`).

### Getting source text of a function

It is possible to get the source text of a function by coercing it to a string — for example, by wrapping it in a template literal:

```js
function foo() {
  return "bar";
}
console.log(`${foo}`);
// function foo() {
// return "bar";
// }
```

This source text is *exact*, including any interspersed comments (which won't be stored by the engine's internal representation otherwise).

```js
function foo /\* a comment \*/() {
  return "bar";
}
console.log(foo.toString());
// function foo /\* a comment \*/() {
// return "bar";
// }
```

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

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

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

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

See also
--------

* `Object.prototype.toString()`


Function: displayName - JavaScript

Function: displayName
=====================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The optional **`displayName`** property of a `Function` instance specifies the display name of the function.

Value
-----

The `displayName` property is not initially present on any function — it's added by the code authors. For the purpose of display, it should be a string.

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

The `displayName` property, if present, may be preferred by consoles and profilers over the `name` property to be displayed as the name of a function.

Among browsers, only the Firefox console utilizes this property. React devtools also use the `displayName` property when displaying the component tree.

Firefox does some basic attempts to decode the `displayName` that's possibly generated by the anonymous JavaScript functions naming convention algorithm. The following patterns are detected:

* If `displayName` ends with a sequence of alphanumeric characters, `_`, and `$`, the longest such suffix is displayed.
* If `displayName` ends with a sequence of `[]`-enclosed characters, that sequence is displayed without the square brackets.
* If `displayName` ends with a sequence of alphanumeric characters and `_` followed by some `/`, `.`, or `<`, the sequence is returned without the trailing `/`, `.`, or `<` characters.
* If `displayName` ends with a sequence of alphanumeric characters and `_` followed by `(^)`, the sequence is displayed without the `(^)`.

If none of the above patterns match, the entire `displayName` is displayed.

Examples
--------

### Setting a displayName

By entering the following in a Firefox console, it should display as something like `function MyFunction()`:

```js
const a = function () {};
a.displayName = "MyFunction";

a; // function MyFunction()
```

### Changing displayName dynamically

You can dynamically change the `displayName` of a function:

```js
const object = {
  // anonymous
  someMethod: function someMethod(value) {
    someMethod.displayName = `someMethod (${value})`;
  },
};

console.log(object.someMethod.displayName); // undefined

object.someMethod("123");
console.log(object.someMethod.displayName); // "someMethod (123)"
```

### Cleaning of displayName

Firefox devtools would clean up a few common patterns in the `displayName` property before displaying it.

```js
function foo() {}

function testName(name) {
  foo.displayName = name;
  console.log(foo);
}

testName("$foo$"); // function $foo$()
testName("foo bar"); // function bar()
testName("Foo.prototype.add"); // function add()
testName("foo ."); // function foo .()
testName("foo <"); // function foo <()
testName("foo?"); // function foo?()
testName("foo()"); // function foo()()

testName("[...]"); // function ...()
testName("foo<"); // function foo()
testName("foo..."); // function foo()
testName("foo(^)"); // function foo()
```

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

Not part of any standard.

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

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

See also
--------

* `Function.prototype.name`


Function.prototype.bind() - JavaScript

Function.prototype.bind()
=========================

The **`bind()`** method of `Function` instances creates a new function that, when called, calls this function with its `this` keyword set to the provided value, and a given sequence of arguments preceding any provided when the new function is called.

Try it
------

Syntax
------

```js
bind(thisArg)
bind(thisArg, arg1)
bind(thisArg, arg1, arg2)
bind(thisArg, arg1, arg2, /\* …, \*/ argN)
```

### Parameters

`thisArg`

The value to be passed as the `this` parameter to the target function `func` when the bound function is called. If the function is not in strict mode, `null` and `undefined` will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the `new` operator.

`arg1`, …, `argN` Optional

Arguments to prepend to arguments provided to the bound function when invoking `func`.

### Return value

A copy of the given function with the specified `this` value, and initial arguments (if provided).

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

The `bind()` function creates a new *bound function*. Calling the bound function generally results in the execution of the function it wraps, which is also called the *target function*. The bound function will store the parameters passed — which include the value of `this` and the first few arguments — as its internal state. These values are stored in advance, instead of being passed at call time. You can generally see `const boundFn = fn.bind(thisArg, arg1, arg2)` as being equivalent to `const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)` for the effect when it's called (but not when `boundFn` is constructed).

A bound function can be further bound by calling `boundFn.bind(thisArg, /* more args */)`, which creates another bound function `boundFn2`. The newly bound `thisArg` value is ignored, because the target function of `boundFn2`, which is `boundFn`, already has a bound `this`. When `boundFn2` is called, it would call `boundFn`, which in turn calls `fn`. The arguments that `fn` ultimately receives are, in order: the arguments bound by `boundFn`, arguments bound by `boundFn2`, and the arguments received by `boundFn2`.

```js
"use strict"; // prevent `this` from being boxed into the wrapper object

function log(...args) {
  console.log(this, ...args);
}
const boundLog = log.bind("this value", 1, 2);
const boundLog2 = boundLog.bind("new this value", 3, 4);
boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6
```

A bound function may also be constructed using the `new` operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided `this` value is ignored (because construction prepares its own `this`, as seen by the parameters of `Reflect.construct`). If the bound function is directly constructed, `new.target` will be the target function instead. (That is, the bound function is transparent to `new.target`.)

```js
class Base {
  constructor(...args) {
    console.log(new.target === Base);
    console.log(args);
  }
}

const BoundBase = Base.bind(null, 1, 2);

new BoundBase(3, 4); // true, [1, 2, 3, 4]
```

However, because a bound function does not have the `prototype` property, it cannot be used as a base class for `extends`.

```js
class Derived extends class {}.bind(null) {}
// TypeError: Class extends value does not have valid prototype property undefined
```

When using a bound function as the right-hand side of `instanceof`, `instanceof` would reach for the target function (which is stored internally in the bound function) and read its `prototype` instead.

```js
class Base {}
const BoundBase = Base.bind(null, 1, 2);
console.log(new Base() instanceof BoundBase); // true
```

The bound function has the following properties:

`length`

The `length` of the target function minus the number of arguments being bound (not counting the `thisArg` parameter), with 0 being the minimum value.

`name`

The `name` of the target function plus a `"bound "` prefix.

The bound function also inherits the prototype chain of the target function. However, it doesn't have other own properties of the target function (such as static properties if the target function is a class).

Examples
--------

### Creating a bound function

The simplest use of `bind()` is to make a function that, no matter how it is called, is called with a particular `this` value.

A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its `this` (e.g., by using the method in callback-based code).

Without special care, however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem:

```js
// Top-level 'this' is bound to 'globalThis' in scripts.
this.x = 9;
const module = {
  x: 81,
  getX() {
    return this.x;
  },
};

// The 'this' parameter of 'getX' is bound to 'module'.
console.log(module.getX()); // 81

const retrieveX = module.getX;
// The 'this' parameter of 'retrieveX' is bound to 'globalThis' in non-strict mode.
console.log(retrieveX()); // 9

// Create a new function 'boundGetX' with the 'this' parameter bound to 'module'.
const boundGetX = retrieveX.bind(module);
console.log(boundGetX()); // 81
```

**Note:** If you run this example in strict mode, the `this` parameter of `retrieveX` will be bound to `undefined` instead of `globalThis`, causing the `retrieveX()` call to fail.

If you run this example in an ECMAScript module, top-level `this` will be bound to `undefined` instead of `globalThis`, causing the `this.x = 9` assignment to fail.

If you run this example in a Node CommonJS module, top-level `this` will be bound to `module.exports` instead of `globalThis`. However, the `this` parameter of `retrieveX` will still be bound to `globalThis` in non-strict mode and to `undefined` in strict mode. Therefore, in non-strict mode (the default), the `retrieveX()` call will return `undefined` because `this.x = 9` is writing to a different object (`module.exports`) from what `getX` is reading from (`globalThis`).

In fact, some built-in "methods" are also getters that return bound functions — one notable example being `Intl.NumberFormat.prototype.format()`, which, when accessed, returns a bound function that you can directly pass as a callback.

### Partially applied functions

The next simplest use of `bind()` is to make a function with pre-specified initial arguments.

These arguments (if any) follow the provided `this` value and are then inserted at the start of the arguments passed to the target function, followed by whatever arguments are passed to the bound function at the time it is called.

```js
function list(...args) {
  return args;
}

function addArguments(arg1, arg2) {
  return arg1 + arg2;
}

console.log(list(1, 2, 3)); // [1, 2, 3]

console.log(addArguments(1, 2)); // 3

// Create a function with a preset leading argument
const leadingThirtySevenList = list.bind(null, 37);

// Create a function with a preset first argument.
const addThirtySeven = addArguments.bind(null, 37);

console.log(leadingThirtySevenList()); // [37]
console.log(leadingThirtySevenList(1, 2, 3)); // [37, 1, 2, 3]
console.log(addThirtySeven(5)); // 42
console.log(addThirtySeven(5, 10)); // 42
// (the last argument 10 is ignored)
```

### With setTimeout()

By default, within `setTimeout()`, the `this` keyword will be set to `globalThis`, which is `window` in browsers. When working with class methods that require `this` to refer to class instances, you may explicitly bind `this` to the callback function, in order to maintain the instance.

```js
class LateBloomer {
  constructor() {
    this.petalCount = Math.floor(Math.random() \* 12) + 1;
  }
  bloom() {
    // Declare bloom after a delay of 1 second
    setTimeout(this.declare.bind(this), 1000);
  }
  declare() {
    console.log(`I am a beautiful flower with ${this.petalCount} petals!`);
  }
}

const flower = new LateBloomer();
flower.bloom();
// After 1 second, calls 'flower.declare()'
```

You can also use arrow functions for this purpose.

```js
class LateBloomer {
  bloom() {
    // Declare bloom after a delay of 1 second
    setTimeout(() => this.declare(), 1000);
  }
}
```

### Bound functions used as constructors

Bound functions are automatically suitable for use with the `new` operator to construct new instances created by the target function. When a bound function is used to construct a value, the provided `this` is ignored. However, provided arguments are still prepended to the constructor call.

```js
function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.toString = function () {
  return `${this.x},${this.y}`;
};

const p = new Point(1, 2);
p.toString();
// '1,2'

// The thisArg's value doesn't matter because it's ignored
const YAxisPoint = Point.bind(null, 0 /\*x\*/);

const axisPoint = new YAxisPoint(5);
axisPoint.toString(); // '0,5'

axisPoint instanceof Point; // true
axisPoint instanceof YAxisPoint; // true
new YAxisPoint(17, 42) instanceof Point; // true
```

Note that you need not do anything special to create a bound function for use with `new`. `new.target`, `instanceof`, `this` etc. all work as expected, as if the constructor was never bound. The only difference is that it can no longer be used for `extends`.

The corollary is that you need not do anything special to create a bound function to be called plainly, even if you would rather require the bound function to only be called using `new`. If you call it without `new`, the bound `this` is suddenly not ignored.

```js
const emptyObj = {};
const YAxisPoint = Point.bind(emptyObj, 0 /\*x\*/);

// Can still be called as a normal function
// (although usually this is undesirable)
YAxisPoint(13);

// The modifications to `this` is now observable from the outside
console.log(emptyObj); // { x: 0, y: 13 }
```

If you wish to restrict a bound function to only be callable with `new`, or only be callable without `new`, the target function must enforce that restriction, such as by checking `new.target !== undefined` or using a class instead.

### Binding classes

Using `bind()` on classes preserves most of the class's semantics, except that all static own properties of the current class are lost. However, because the prototype chain is preserved, you can still access static properties inherited from the parent class.

```js
class Base {
  static baseProp = "base";
}

class Derived extends Base {
  static derivedProp = "derived";
}

const BoundDerived = Derived.bind(null);
console.log(BoundDerived.baseProp); // "base"
console.log(BoundDerived.derivedProp); // undefined
console.log(new BoundDerived() instanceof Derived); // true
```

### Transforming methods to utility functions

`bind()` is also helpful in cases where you want to transform a method which requires a specific `this` value to a plain utility function that accepts the previous `this` parameter as a normal parameter. This is similar to how general-purpose utility functions work: instead of calling `array.map(callback)`, you use `map(array, callback)`, which avoids mutating `Array.prototype`, and allows you to use `map` with array-like objects that are not arrays (for example, `arguments`).

Take `Array.prototype.slice()`, for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this:

```js
const slice = Array.prototype.slice;

// ...

slice.call(arguments);
```

Note that you can't save `slice.call` and call it as a plain function, because the `call()` method also reads its `this` value, which is the function it should call. In this case, you can use `bind()` to bind the value of `this` for `call()`. In the following piece of code, `slice()` is a bound version of `Function.prototype.call()`, with the `this` value bound to `Array.prototype.slice()`. This means that additional `call()` calls can be eliminated:

```js
// Same as "slice" in the previous example
const unboundSlice = Array.prototype.slice;
const slice = Function.prototype.call.bind(unboundSlice);

// ...

slice(arguments);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-function.prototype.bind |

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

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

See also
--------

* Polyfill of `Function.prototype.bind` in `core-js`
* `Function.prototype.apply()`
* `Function.prototype.call()`
* Functions


Function.prototype.apply() - JavaScript

Function.prototype.apply()
==========================

The **`apply()`** method of `Function` instances calls this function with a given `this` value, and `arguments` provided as an array (or an array-like object).

Try it
------

Syntax
------

```js
apply(thisArg)
apply(thisArg, argsArray)
```

### Parameters

`thisArg`

The value of `this` provided for the call to `func`. If the function is not in strict mode, `null` and `undefined` will be replaced with the global object, and primitive values will be converted to objects.

`argsArray` Optional

An array-like object, specifying the arguments with which `func` should be called, or `null` or `undefined` if no arguments should be provided to the function.

### Return value

The result of calling the function with the specified `this` value and arguments.

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

**Note:** This function is almost identical to `call()`, except that the function arguments are passed to `call()` individually as a list, while for `apply()` they are combined in one object, typically an array — for example, `func.call(this, "eat", "bananas")` vs. `func.apply(this, ["eat", "bananas"])`.

Normally, when calling a function, the value of `this` inside the function is the object that the function was accessed on. With `apply()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions.

You can also use any kind of object which is array-like as the second parameter. In practice, this means that it needs to have a `length` property, and integer ("index") properties in the range `(0..length - 1)`. For example, you could use a `NodeList`, or a custom object like `{ 'length': 2, '0': 'eat', '1': 'bananas' }`. You can also use `arguments`, for example:

```js
function wrapper() {
  return anotherFn.apply(null, arguments);
}
```

With the rest parameters and parameter spread syntax, this can be rewritten as:

```js
function wrapper(...args) {
  return anotherFn(...args);
}
```

In general, `fn.apply(null, args)` is equivalent to `fn(...args)` with the parameter spread syntax, except `args` is expected to be an array-like object in the former case with `apply()`, and an iterable object in the latter case with spread syntax.

**Warning:** Do not use `apply()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means `new.target` is `undefined`, and classes throw an error because they can't be called without `new`. Use `Reflect.construct()` or `extends` instead.

Examples
--------

### Using apply() to append an array to another

You can use `Array.prototype.push()` to append an element to an array. Because `push()` accepts a variable number of arguments, you can also push multiple elements at once. But if you pass an array to `push()`, it will actually add that array as a single element, instead of adding the elements individually, ending up with an array inside an array. On the other hand, `Array.prototype.concat()` does have the desired behavior in this case, but it does not append to the *existing* array — it creates and returns a new array.

In this case, you can use `apply` to implicitly "spread" an array as a series of arguments.

```js
const array = ["a", "b"];
const elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]
```

The same effect can be achieved with the spread syntax.

```js
const array = ["a", "b"];
const elements = [0, 1, 2];
array.push(...elements);
console.info(array); // ["a", "b", 0, 1, 2]
```

### Using apply() and built-in functions

Clever usage of `apply()` allows you to use built-in functions for some tasks that would probably otherwise require manually looping over a collection (or using the spread syntax).

For example, we can use `Math.max()` and `Math.min()` to find out the maximum and minimum value in an array.

```js
// min/max number in an array
const numbers = [5, 6, 2, 3, 7];

// using Math.min/Math.max apply
let max = Math.max.apply(null, numbers);
// This about equal to Math.max(numbers[0], …)
// or Math.max(5, 6, …)

let min = Math.min.apply(null, numbers);

// vs. simple loop based algorithm
max = -Infinity;
min = +Infinity;

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] > max) {
    max = numbers[i];
  }
  if (numbers[i] < min) {
    min = numbers[i];
  }
}
```

But beware: by using `apply()` (or the spread syntax) with an arbitrarily long arguments list, you run the risk of exceeding the JavaScript engine's argument length limit.

The consequences of calling a function with too many arguments (that is, more than tens of thousands of arguments) is unspecified and varies across engines. (The JavaScriptCore engine has a hard-coded argument limit of 65536.) Most engines throw an exception; but there's no normative specification preventing other behaviors, such as arbitrarily limiting the number of arguments actually passed to the applied function. To illustrate this latter case: if such an engine had a limit of four arguments (actual limits are of course significantly higher), it would be as if the arguments `5, 6, 2, 3` had been passed to `apply` in the examples above, rather than the full array.

If your value array might grow into the tens of thousands, use a hybrid strategy: apply your function to chunks of the array at a time:

```js
function minOfArray(arr) {
  let min = Infinity;
  const QUANTUM = 32768;

  for (let i = 0; i < arr.length; i += QUANTUM) {
    const submin = Math.min.apply(
      null,
      arr.slice(i, Math.min(i + QUANTUM, arr.length)),
    );
    min = Math.min(submin, min);
  }

  return min;
}

const min = minOfArray([5, 6, 2, 3, 7]);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-function.prototype.apply |

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

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

See also
--------

* `arguments`
* `Function.prototype.bind()`
* `Function.prototype.call()`
* `Reflect.apply()`
* Functions
* Spread syntax (`...`)


Function() constructor - JavaScript

Function() constructor
======================

The **`Function()`** constructor creates `Function` objects. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as `eval()`. However, unlike `eval` (which may have access to the local scope), the `Function` constructor creates functions which execute in the global scope only.

Try it
------

Syntax
------

```js
new Function(functionBody)
new Function(arg1, functionBody)
new Function(arg1, arg2, functionBody)
new Function(arg1, arg2, /\* …, \*/ argN, functionBody)

Function(functionBody)
Function(arg1, functionBody)
Function(arg1, arg2, functionBody)
Function(arg1, arg2, /\* …, \*/ argN, functionBody)
```

**Note:** `Function()` can be called with or without `new`. Both create a new `Function` instance.

### Parameters

`arg1`, …, `argN` Optional

Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain identifier, rest parameter, or destructured parameter, optionally with a default), or a list of such strings separated with commas.

As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: `"x", "theValue = 42", "[a, b] /* numbers */"` — or `"x, theValue = 42, [a, b] /* numbers */"`. (`"x, theValue = 42", "[a, b]"` is also correct, though very confusing to read.)

`functionBody`

A string containing the JavaScript statements comprising the function definition.

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

`Function` objects created with the `Function` constructor are parsed when the function is created. This is less efficient than creating a function with a function expression or function declaration and calling it within your code, because such functions are parsed with the rest of the code.

All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion:

```js
`function anonymous(${args.join(",")}
) {
${functionBody}
}`;
```

This is observable by calling the function's `toString()` method.

However, unlike normal function expressions, the name `anonymous` is not added to the `functionBody`'s scope, since `functionBody` only has access the global scope. If `functionBody` is not in strict mode (the body itself needs to have the `"use strict"` directive since it doesn't inherit the strictness from the context), you may use `arguments.callee` to refer to the function itself. Alternatively, you can define the recursive part as an inner function:

```js
const recursiveFn = new Function(
  "count",
  `
(function recursiveFn(count) {
 if (count < 0) {
 return;
 }
 console.log(count);
 recursiveFn(count - 1);
})(count);
`,
);
```

Note that the two dynamic parts of the assembled source — the parameters list `args.join(",")` and `functionBody` — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts.

```js
new Function("/\*", "\*/) {");
// SyntaxError: Unexpected end of arg string
// Doesn't become "function anonymous(/\*) {\*/) {}"
```

Examples
--------

### Specifying arguments with the Function constructor

The following code creates a `Function` object that takes two arguments.

```js
// Example can be run directly in your JavaScript console

// Create a function that takes two arguments, and returns the sum of those arguments
const adder = new Function("a", "b", "return a + b");

// Call the function
adder(2, 6);
// 8
```

The arguments `a` and `b` are formal argument names that are used in the function body, `return a + b`.

### Creating a function object from a function declaration or function expression

```js
// The function constructor can take in multiple statements separated by a semicolon. Function expressions require a return statement with the function's name

// Observe that new Function is called. This is so we can call the function we created directly afterwards
const sumOfArray = new Function(
  "const sumArray = (arr) => arr.reduce((previousValue, currentValue) => previousValue + currentValue); return sumArray",
)();

// call the function
sumOfArray([1, 2, 3, 4]);
// 10

// If you don't call new Function at the point of creation, you can use the Function.call() method to call it
const findLargestNumber = new Function(
  "function findLargestNumber (arr) { return Math.max(...arr) }; return findLargestNumber",
);

// call the function
findLargestNumber.call({}).call({}, [2, 4, 1, 8, 5]);
// 8

// Function declarations do not require a return statement
const sayHello = new Function(
  "return function (name) { return `Hello, ${name}` }",
)();

// call the function
sayHello("world");
// Hello, world
```

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

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

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

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

See also
--------

* `function`
* `function` expression
* Functions


Function: length - JavaScript

Function: length
================

The **`length`** data property of a `Function` instance indicates the number of parameters expected by the function.

Try it
------

Value
-----

A number.

| Property attributes of `Function: length` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | yes |

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

A `Function` object's `length` property indicates how many arguments the function expects, i.e. the number of formal parameters. This number excludes the rest parameter and only includes parameters before the first one with a default value. By contrast, `arguments.length` is local to a function and provides the number of arguments actually passed to the function.

The `Function` constructor is itself a `Function` object. Its `length` data property has a value of `1`.

Due to historical reasons, `Function.prototype` is a callable itself. The `length` property of `Function.prototype` has a value of `0`.

Examples
--------

### Using function length

```js
console.log(Function.length); // 1

console.log((() => {}).length); // 0
console.log(((a) => {}).length); // 1
console.log(((a, b) => {}).length); // 2 etc.

console.log(((...args) => {}).length);
// 0, rest parameter is not counted

console.log(((a, b = 1, c) => {}).length);
// 1, only parameters before the first one with
// a default value are counted
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-function-instances-length |

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

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

See also
--------

* `Function`


Function.prototype.caller - JavaScript

Function.prototype.caller
=========================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

**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:** In strict mode, accessing `caller` of a function throws an error — the API is removed with no replacement. This is to prevent code from being able to "walk the stack", which both poses security risks and severely limits the possibility of optimizations like inlining and tail-call optimization. For more explanation, you can read the rationale for the deprecation of `arguments.callee`.

The **`caller`** accessor property of `Function` instances returns the function that invoked this function. For strict, arrow, async, and generator functions, accessing the `caller` property throws a `TypeError`.

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

If the function `f` was invoked by the top-level code, the value of `f.caller` is `null`; otherwise it's the function that called `f`. If the function that called `f` is a strict mode function, the value of `f.caller` is also `null`.

Note that the only behavior specified by the ECMAScript specification is that `Function.prototype` has an initial `caller` accessor that unconditionally throws a `TypeError` for any `get` or `set` request (known as a "poison pill accessor"), and that implementations are not allowed to change this semantic for any function except non-strict plain functions, in which case it must not have the value of a strict mode function. The actual behavior of the `caller` property, if it's anything other than throwing an error, is implementation-defined. For example, Chrome defines it as an own data property, while Firefox and Safari extend the initial poison-pill `Function.prototype.caller` accessor to specially handle `this` values that are non-strict functions.

```js
(function f() {
  if (Object.hasOwn(f, "caller")) {
    console.log(
      "caller is an own property with descriptor",
      Object.getOwnPropertyDescriptor(f, "caller"),
    );
  } else {
    console.log(
      "f doesn't have an own property named caller. Trying to get f.[[Prototype]].caller",
    );
    console.log(
      Object.getOwnPropertyDescriptor(
        Object.getPrototypeOf(f),
        "caller",
      ).get.call(f),
    );
  }
})();

// In Chrome:
// caller is an own property with descriptor {value: null, writable: false, enumerable: false, configurable: false}

// In Firefox:
// f doesn't have an own property named caller. Trying to get f.[[Prototype]].caller
// null
```

This property replaces the obsolete `arguments.caller` property of the `arguments` object.

The special property `__caller__`, which returned the activation object of the caller thus allowing to reconstruct the stack, was removed for security reasons.

Examples
--------

### Checking the value of a function's caller property

The following code checks the value a function's `caller` property.

```js
function myFunc() {
  if (myFunc.caller === null) {
    return "The function was called from the top!";
  } else {
    return `This function's caller was ${myFunc.caller}`;
  }
}
```

### Reconstructing the stack and recursion

Note that in case of recursion, you can't reconstruct the call stack using this property. Consider:

```js
function f(n) {
  g(n - 1);
}
function g(n) {
  if (n > 0) {
    f(n);
  } else {
    stop();
  }
}
f(2);
```

At the moment `stop()` is called the call stack will be:
```

f(2) -> g(1) -> f(1) -> g(0) -> stop()
```

The following is true:

```js
stop.caller === g && f.caller === g && g.caller === f;
```

so if you tried to get the stack trace in the `stop()` function like this:

```js
let f = stop;
let stack = "Stack trace:";
while (f) {
  stack += `\n${f.name}`;
  f = f.caller;
}
```

the loop would never stop.

### Strict mode caller

If the caller is a strict mode function, the value of `caller` is `null`.

```js
function callerFunc() {
  calleeFunc();
}

function strictCallerFunc() {
  "use strict";
  calleeFunc();
}

function calleeFunc() {
  console.log(calleeFunc.caller);
}

(function () {
  callerFunc();
})();
// Logs [Function: callerFunc]

(function () {
  strictCallerFunc();
})();
// Logs null
```

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

Not part of any standard.

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

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

See also
--------

* `Function.prototype.name`
* `arguments`


Function: prototype - JavaScript

Function: prototype
===================

The **`prototype`** data property of a `Function` instance is used when the function is used as a constructor with the `new` operator. It will become the new object's prototype.

**Note:** Not all `Function` objects have the `prototype` property — see description.

Value
-----

An object.

| Property attributes of `Function: prototype` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | no |

**Note:** The `prototype` property of classes is not writable.

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

When a function is called with `new`, the constructor's `prototype` property will become the resulting object's prototype.

```js
function Ctor() {}
const inst = new Ctor();
console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true
```

You can read Inheritance and the prototype chain for more information about the interactions between a constructor function's `prototype` property and the resulting object's prototype.

A function having a `prototype` property is not sufficient for it to be eligible as a constructor. Generator functions have a `prototype` property, but cannot be called with `new`:

```js
async function\* asyncGeneratorFunction() {}
function\* generatorFunction() {}
```

Instead, generator functions' `prototype` property is used when they are called *without* `new`. The `prototype` property will become the returned `Generator` object's prototype.

In addition, some functions may have a `prototype` but throw unconditionally when called with `new`. For example, the `Symbol()` and `BigInt()` functions throw when called with `new`, because `Symbol.prototype` and `BigInt.prototype` are only intended to provide methods for the primitive values, but the wrapper objects should not be directly constructed.

The following functions do not have `prototype`, and are therefore ineligible as constructors, even if a `prototype` property is later manually assigned:

```js
const method = { foo() {} }.foo;
const arrowFunction = () => {};
async function asyncFunction() {}
```

The following are valid constructors that have `prototype`:

```js
class Class {}
function fn() {}
```

A bound function does not have a `prototype` property, but may be constructable. When it's constructed, the target function is constructed instead, and if the target function is constructable, it would return a normal instance.

```js
const boundFunction = function () {}.bind(null);
```

A function's `prototype` property, by default, is a plain object with one property: `constructor`, which is a reference to the function itself. The `constructor` property is writable, non-enumerable, and configurable.

If the `prototype` of a function is reassigned with something other than an `Object`, when the function is called with `new`, the returned object's prototype would be `Object.prototype` instead. (In other words, `new` ignores the `prototype` property and constructs a plain object.)

```js
function Ctor() {}
Ctor.prototype = 3;
console.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true
```

Examples
--------

### Changing the prototype of all instances by mutating the prototype property

```js
function Ctor() {}
const p1 = new Ctor();
const p2 = new Ctor();
Ctor.prototype.prop = 1;
console.log(p1.prop); // 1
console.log(p2.prop); // 1
```

### Adding a non-method property to a class's prototype property

Class fields add properties to each instance. Class methods declare *function* properties on the prototype. However, there's no way to add a non-function property to the prototype. In case you want to share static data between all instances (for example, `Error.prototype.name` is the same between all error instances), you can manually assign it on the `prototype` of a class.

```js
class Dog {
  constructor(name) {
    this.name = name;
  }
}

Dog.prototype.species = "dog";

console.log(new Dog("Jack").species); // "dog"
```

This can be made more ergonomic using static initialization blocks, which are called when the class is initialized.

```js
class Dog {
  static {
    Dog.prototype.species = "dog";
  }
  constructor(name) {
    this.name = name;
  }
}

console.log(new Dog("Jack").species); // "dog"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-function-instances-prototype |

See also
--------

* `Function`
* Inheritance and the prototype chain


Function: name - JavaScript

Function: name
==============

The **`name`** data property of a `Function` instance indicates the function's name as specified when it was created, or it may be either `anonymous` or `''` (an empty string) for functions created anonymously.

Try it
------

Value
-----

A string.

| Property attributes of `Function: name` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | yes |

**Note:** In non-standard, pre-ES2015 implementations the `configurable` attribute was `false` as well.

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

The function's `name` property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself.

The `name` property is read-only and cannot be changed by the assignment operator:

```js
function someFunction() {}

someFunction.name = "otherFunction";
console.log(someFunction.name); // someFunction
```

To change it, use `Object.defineProperty()`.

The `name` property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred.

### Function declaration

The `name` property returns the name of a function declaration.

```js
function doSomething() {}
doSomething.name; // "doSomething"
```

### Default-exported function declaration

An `export default` declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is `"default"`.

```js
// -- someModule.js --
export default function () {}

// -- main.js --
import someModule from "./someModule.js";

someModule.name; // "default"
```

### Function constructor

Functions created with the `Function()` constructor have name "anonymous".

```js
new Function().name; // "anonymous"
```

### Function expression

If the function expression is named, that name is used as the `name` property.

```js
const someFunction = function someFunctionName() {};
someFunction.name; // "someFunctionName"
```

Anonymous function expressions created using the keyword `function` or arrow functions would have `""` (an empty string) as their name.

```js
(function () {}).name; // ""
(() => {}).name; // ""
```

However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate.

One practical case where the name cannot be inferred is a function returned from another function:

```js
function getFoo() {
  return () => {};
}
getFoo().name; // ""
```

### Variable declaration and method

Variables and methods can infer the name of an anonymous function from its syntactic position.

```js
const f = function () {};
const object = {
  someMethod: function () {},
};

console.log(f.name); // "f"
console.log(object.someMethod.name); // "someMethod"
```

The same applies to assignment:

```js
let f;
f = () => {};
f.name; // "f"
```

### Initializer and default value

Functions in initializers (default values) of destructuring, default parameters, class fields, etc., will inherit the name of the bound identifier as their `name`.

```js
const [f = () => {}] = [];
f.name; // "f"

const { someMethod: m = () => {} } = {};
m.name; // "m"

function foo(f = () => {}) {
  console.log(f.name);
}
foo(); // "f"

class Foo {
  static someMethod = () => {};
}
Foo.someMethod.name; // someMethod
```

### Shorthand method

```js
const o = {
  foo() {},
};
o.foo.name; // "foo";
```

### Bound function

`Function.prototype.bind()` produces a function whose name is "bound " plus the function name.

```js
function foo() {}
foo.bind({}).name; // "bound foo"
```

### Getter and setter

When using `get` and `set` accessor properties, "get" or "set" will appear in the function name.

```js
const o = {
  get foo() {},
  set foo(x) {},
};

const descriptor = Object.getOwnPropertyDescriptor(o, "foo");
descriptor.get.name; // "get foo"
descriptor.set.name; // "set foo";
```

### Class

A class's name follows the same algorithm as function declarations and expressions.

```js
class Foo {}
Foo.name; // "Foo"
```

**Warning:** JavaScript will set the function's `name` property only if a function does not have an own property called `name`. However, classes' static members will be set as own properties of the class constructor function, and thus prevent the built-in `name` from being applied. See an example below.

### Symbol as function name

If a `Symbol` is used a function name and the symbol has a description, the method's name is the description in square brackets.

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

const o = {
  [sym1]() {},
  [sym2]() {},
};

o[sym1].name; // "[foo]"
o[sym2].name; // "[]"
```

### Private property

Private fields and private methods have the hash (`#`) as part of their names.

```js
class Foo {
  #field = () => {};
  #method() {}
  getNames() {
    console.log(this.#field.name);
    console.log(this.#method.name);
  }
}

new Foo().getNames();
// "#field"
// "#method"
```

Examples
--------

### Telling the constructor name of an object

You can use `obj.constructor.name` to check the "class" of an object.

```js
function Foo() {} // Or: class Foo {}

const fooInstance = new Foo();
console.log(fooInstance.constructor.name); // "Foo"
```

However, because static members will become own properties of the class, we can't obtain the class name for virtually any class with a static method property `name()`:

```js
class Foo {
  constructor() {}
  static name() {}
}
```

With a `static name()` method `Foo.name` no longer holds the actual class name but a reference to the `name()` function object. Trying to obtain the class of `fooInstance` via `fooInstance.constructor.name` won't give us the class name at all, but instead a reference to the static class method. Example:

```js
const fooInstance = new Foo();
console.log(fooInstance.constructor.name); // ƒ name() {}
```

Due to the existence of static fields, `name` may not be a function either.

```js
class Foo {
  static name = 123;
}
console.log(new Foo().constructor.name); // 123
```

If a class has a static property called `name`, it will also become *writable*. The built-in definition in the absence of a custom static definition is *read-only*:

```js
Foo.name = "Hello";
console.log(Foo.name); // "Hello" if class Foo has a static "name" property, but "Foo" if not.
```

Therefore you may not rely on the built-in `name` property to always hold a class's name.

### JavaScript compressors and minifiers

**Warning:** Be careful when using the `name` property with source-code transformations, such as those carried out by JavaScript compressors (minifiers) or obfuscators. These tools are often used as part of a JavaScript build pipeline to reduce the size of a program prior to deploying it to production. Such transformations often change a function's name at build time.

Source code such as:

```js
function Foo() {}
const foo = new Foo();

if (foo.constructor.name === "Foo") {
  console.log("'foo' is an instance of 'Foo'");
} else {
  console.log("Oops!");
}
```

may be compressed to:

```js
function a() {}
const b = new a();
if (b.constructor.name === "Foo") {
  console.log("'foo' is an instance of 'Foo'");
} else {
  console.log("Oops!");
}
```

In the uncompressed version, the program runs into the truthy branch and logs "'foo' is an instance of 'Foo'" — whereas, in the compressed version it behaves differently, and runs into the else branch. If you rely on the `name` property, like in the example above, make sure your build pipeline doesn't change function names, or don't assume a function has a particular name.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-function-instances-name |

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

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

See also
--------

* Polyfill for `Function: name` in `core-js`
* `Function`


Function.prototype.call() - JavaScript

Function.prototype.call()
=========================

The **`call()`** method of `Function` instances calls this function with a given `this` value and arguments provided individually.

Try it
------

Syntax
------

```js
call(thisArg)
call(thisArg, arg1)
call(thisArg, arg1, arg2)
call(thisArg, arg1, arg2, /\* …, \*/ argN)
```

### Parameters

`thisArg`

The value to use as `this` when calling `func`. If the function is not in strict mode, `null` and `undefined` will be replaced with the global object, and primitive values will be converted to objects.

`arg1`, …, `argN` Optional

Arguments for the function.

### Return value

The result of calling the function with the specified `this` value and arguments.

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

**Note:** This function is almost identical to `apply()`, except that the function arguments are passed to `call()` individually as a list, while for `apply()` they are combined in one object, typically an array — for example, `func.call(this, "eat", "bananas")` vs. `func.apply(this, ["eat", "bananas"])`.

Normally, when calling a function, the value of `this` inside the function is the object that the function was accessed on. With `call()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions.

**Warning:** Do not use `call()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means `new.target` is `undefined`, and classes throw an error because they can't be called without `new`. Use `Reflect.construct()` or `extends` instead.

Examples
--------

### Using call() to invoke a function and specifying the this value

In the example below, when we call `greet`, the value of `this` will be bound to object `obj`, even when `greet` is not a method of `obj`.

```js
function greet() {
  console.log(this.animal, "typically sleep between", this.sleepDuration);
}

const obj = {
  animal: "cats",
  sleepDuration: "12 and 16 hours",
};

greet.call(obj); // cats typically sleep between 12 and 16 hours
```

### Using call() to invoke a function without specifying the first argument

If the first `thisArg` parameter is omitted, it defaults to `undefined`. In non-strict mode, the `this` value is then substituted with `globalThis` (which is akin to the global object).

```js
globalThis.globProp = "Wisen";

function display() {
  console.log(`globProp value is ${this.globProp}`);
}

display.call(); // Logs "globProp value is Wisen"
```

In strict mode, the value of `this` is not substituted, so it stays as `undefined`.

```js
"use strict";

globalThis.globProp = "Wisen";

function display() {
  console.log(`globProp value is ${this.globProp}`);
}

display.call(); // throws TypeError: Cannot read the property of 'globProp' of undefined
```

### Transforming methods to utility functions

`call()` is almost equivalent to a normal function call, except that `this` is passed as a normal parameter instead of as the value that the function was accessed on. This is similar to how general-purpose utility functions work: instead of calling `array.map(callback)`, you use `map(array, callback)`, which avoids mutating `Array.prototype`, and allows you to use `map` with array-like objects that are not arrays (for example, `arguments`).

Take `Array.prototype.slice()`, for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this:

```js
const slice = Array.prototype.slice;

// ...

slice.call(arguments);
```

Note that you can't save `slice.call` and call it as a plain function, because the `call()` method also reads its `this` value, which is the function it should call. In this case, you can use `bind()` to bind the value of `this` for `call()`. In the following piece of code, `slice()` is a bound version of `Function.prototype.call()`, with the `this` value bound to `Array.prototype.slice()`. This means that additional `call()` calls can be eliminated:

```js
// Same as "slice" in the previous example
const unboundSlice = Array.prototype.slice;
const slice = Function.prototype.call.bind(unboundSlice);

// ...

slice(arguments);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-function.prototype.call |

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

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

See also
--------

* `Function.prototype.bind()`
* `Function.prototype.apply()`
* `Reflect.apply()`
* Spread syntax (`...`)
* Introduction to Object-Oriented JavaScript


Set.prototype.clear() - JavaScript

Set.prototype.clear()
=====================

The **`clear()`** method of `Set` instances removes all elements from this set.

Try it
------

Syntax
------

```js
clear()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

### Using the clear() method

```js
const mySet = new Set();
mySet.add(1);
mySet.add("foo");

console.log(mySet.size); // 2
console.log(mySet.has("foo")); // true

mySet.clear();

console.log(mySet.size); // 0
console.log(mySet.has("foo")); // false
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype.clear |

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

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

See also
--------

* `Set`
* `Set.prototype.delete()`