Array.prototype.toLocaleString() - JavaScript

Array.prototype.toLocaleString()
================================

 The **`toLocaleString()`** method of `Array` instances returns a string representing
 the elements of the array. The elements are converted to strings using their
 `toLocaleString` methods and these strings are separated by a locale-specific
 string (such as a comma ",").

Try it
------

Syntax
------

```js
toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)
```

### Parameters

`locales` Optional

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see the parameter description on the `Intl` main page.

`options` Optional

An object with configuration properties. For numbers, see `Number.prototype.toLocaleString()`; for dates, see `Date.prototype.toLocaleString()`.

### Return value

A string representing the elements of the array.

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

The `Array.prototype.toLocaleString` method traverses its content, calling the `toLocaleString` method of every element with the `locales` and `options` parameters provided, and concatenates them with an implementation-defined separator (such as a comma ","). Note that the method itself does not consume the two parameters — it only passes them to the `toLocaleString()` of each element. The choice of the separator string depends on the host's current locale, not the `locales` parameter.

If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`.

When used on sparse arrays, the `toLocaleString()` method iterates empty slots as if they have the value `undefined`.

The `toLocaleString()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Using locales and options

 The elements of the array are converted to strings using their
 `toLocaleString` methods.

* `Object`: `Object.prototype.toLocaleString()`
* `Number`: `Number.prototype.toLocaleString()`
* `Date`: `Date.prototype.toLocaleString()`

 Always display the currency for the strings and numbers in the `prices`
 array:

```js
const prices = ["￥7", 500, 8123, 12];
prices.toLocaleString("ja-JP", { style: "currency", currency: "JPY" });

// "￥7,￥500,￥8,123,￥12"
```

For more examples, see also the `Intl.NumberFormat` and `Intl.DateTimeFormat` pages.

### Using toLocaleString() on sparse arrays

`toLocaleString()` treats empty slots the same as `undefined` and produces an extra separator:

```js
console.log([1, , 3].toLocaleString()); // '1,,3'
```

### Calling toLocaleString() on non-array objects

The `toLocaleString()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.

```js
const arrayLike = {
  length: 3,
  0: 1,
  1: 2,
  2: 3,
  3: 4, // ignored by toLocaleString() since length is 3
};
console.log(Array.prototype.toLocaleString.call(arrayLike));
// 1,2,3
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.tolocalestring |
| ECMAScript Internationalization API Specification # sup-array.prototype.tolocalestring |

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

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

See also
--------

* Indexed collections guide
* `Array`
* `Array.prototype.toString()`
* `TypedArray.prototype.toLocaleString()`
* `Intl`
* `Intl.ListFormat`
* `Object.prototype.toLocaleString()`
* `Number.prototype.toLocaleString()`
* `Date.prototype.toLocaleString()`


Array.prototype.reverse() - JavaScript

Array.prototype.reverse()
=========================

The **`reverse()`** method of `Array` instances reverses an array *in place* and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated.

To reverse the elements in an array without mutating the original array, use `toReversed()`.

Try it
------

Syntax
------

```js
reverse()
```

### Parameters

None.

### Return value

The reference to the original array, now reversed. Note that the array is reversed *in place*, and no copy is made.

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

 The `reverse()` method transposes the elements of the calling array object in
 place, mutating the array, and returning a reference to the array.

The `reverse()` method preserves empty slots. If the source array is sparse, the empty slots' corresponding new indices are deleted and also become empty slots.

The `reverse()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

Examples
--------

### Reversing the elements in an array

 The following example creates an array `items`, containing three elements, then
 reverses the array. The call to `reverse()` returns a reference to the
 reversed array `items`.

```js
const items = [1, 2, 3];
console.log(items); // [1, 2, 3]

items.reverse();
console.log(items); // [3, 2, 1]
```

### The reverse() method returns the reference to the same array

The `reverse()` method returns reference to the original array, so mutating the returned array will mutate the original array as well.

```js
const numbers = [3, 2, 4, 1, 5];
const reversed = numbers.reverse();
// numbers and reversed are both in reversed order [5, 1, 4, 2, 3]
reversed[0] = 5;
console.log(numbers[0]); // 5
```

In case you want `reverse()` to not mutate the original array, but return a shallow-copied array like other array methods (e.g. `map()`) do, use the `toReversed()` method. Alternatively, you can do a shallow copy before calling `reverse()`, using the spread syntax or `Array.from()`.

```js
const numbers = [3, 2, 4, 1, 5];
// [...numbers] creates a shallow copy, so reverse() does not mutate the original
const reverted = [...numbers].reverse();
reverted[0] = 5;
console.log(numbers[0]); // 3
```

### Using reverse() on sparse arrays

Sparse arrays remain sparse after calling `reverse()`. Empty slots are copied over to their respective new indices as empty slots.

```js
console.log([1, , 3].reverse()); // [3, empty, 1]
console.log([1, , 3, 4].reverse()); // [4, 3, empty, 1]
```

### Calling reverse() on non-array objects

The `reverse()` method reads the `length` property of `this`. It then visits each property having an integer key between `0` and `length / 2`, and swaps the two corresponding indices on both ends, deleting any destination property for which the source property did not exist.

```js
const arrayLike = {
  length: 3,
  unrelated: "foo",
  2: 4,
  3: 33, // ignored by reverse() since length is 3
};
console.log(Array.prototype.reverse.call(arrayLike));
// { 0: 4, 3: 33, length: 3, unrelated: 'foo' }
// The index 2 is deleted because there was no index 0 present originally
// The index 3 is unchanged since the length is 3
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.reverse |

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

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

See also
--------

* Polyfill of `Array.prototype.reverse` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.join()`
* `Array.prototype.sort()`
* `Array.prototype.toReversed()`
* `TypedArray.prototype.reverse()`


Array.prototype.fill() - JavaScript

Array.prototype.fill()
======================

The **`fill()`** method of `Array` instances changes all elements within a range of indices in an array to a static value. It returns the modified array.

Try it
------

Syntax
------

```js
fill(value)
fill(value, start)
fill(value, start, end)
```

### Parameters

`value`

Value to fill the array with. Note all elements in the array will be this exact value: if `value` is an object, each slot in the array will reference that object.

`start` Optional

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

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

`end` Optional

Zero-based index at which to end filling, converted to an integer. `fill()` fills up to but not including `end`.

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

### Return value

The modified array, filled with `value`.

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

The `fill()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this`.

The `fill()` method fills empty slots in sparse arrays with `value` as well.

The `fill()` method is generic. It only expects the `this` value to have a `length` property. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

**Note:** Using `Array.prototype.fill()` on an empty array (`length = 0`) would not modify it as the array has nothing to be modified.
 To use `Array.prototype.fill()` when declaring an array, make sure the array has non-zero `length`.
 See example.

Examples
--------

### Using fill()

```js
console.log([1, 2, 3].fill(4)); // [4, 4, 4]
console.log([1, 2, 3].fill(4, 1)); // [1, 4, 4]
console.log([1, 2, 3].fill(4, 1, 2)); // [1, 4, 3]
console.log([1, 2, 3].fill(4, 1, 1)); // [1, 2, 3]
console.log([1, 2, 3].fill(4, 3, 3)); // [1, 2, 3]
console.log([1, 2, 3].fill(4, -3, -2)); // [4, 2, 3]
console.log([1, 2, 3].fill(4, NaN, NaN)); // [1, 2, 3]
console.log([1, 2, 3].fill(4, 3, 5)); // [1, 2, 3]
console.log(Array(3).fill(4)); // [4, 4, 4]

// A single object, referenced by each slot of the array:
const arr = Array(3).fill({}); // [{}, {}, {}]
arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]
```

### Using fill() to create a matrix of all 1

This example shows how to create a matrix of all 1, like the `ones()` function of Octave or MATLAB.

```js
const arr = new Array(3);
for (let i = 0; i < arr.length; i++) {
  arr[i] = new Array(4).fill(1); // Creating an array of size 4 and filled of 1
}
arr[0][0] = 10;
console.log(arr[0][0]); // 10
console.log(arr[1][0]); // 1
console.log(arr[2][0]); // 1
```

### Using fill() to populate an empty array

 This example shows how to populate an array, setting all elements to a specific value.
 The `end` parameter does not have to be specified.

```js
const tempGirls = Array(5).fill("girl", 0);
```

Note that the array was initially a sparse array with no assigned indices. `fill()` is still able to fill this array.

### Calling fill() on non-array objects

The `fill()` method reads the `length` property of `this` and sets the value of each integer-keyed property from `start` to `end`.

```js
const arrayLike = { length: 2 };
console.log(Array.prototype.fill.call(arrayLike, 1));
// { '0': 1, '1': 1, length: 2 }
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.fill |

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

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

See also
--------

* Polyfill of `Array.prototype.fill` in `core-js`
* Indexed collections guide
* `Array`
* `TypedArray.prototype.fill()`


Array.fromAsync() - JavaScript

Array.fromAsync()
=================

The **`Array.fromAsync()`** static method creates a new, shallow-copied `Array` instance from an async iterable, iterable, or array-like object.

Syntax
------

```js
Array.fromAsync(arrayLike)
Array.fromAsync(arrayLike, mapFn)
Array.fromAsync(arrayLike, mapFn, thisArg)
```

### Parameters

`arrayLike`

An async iterable, iterable, or array-like object to convert to an array.

`mapFn` Optional

A function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the array instead (after being awaited). The function is called with the following arguments:

`element`

The current element being processed in the array. Because all elements are first awaited, this value will never be a thenable.

`index`

The index of the current element being processed in the array.

`thisArg` Optional

Value to use as `this` when executing `mapFn`.

### Return value

A new `Promise` whose fulfillment value is a new `Array` instance.

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

`Array.fromAsync()` lets you create arrays from:

* async iterable objects (objects such as `ReadableStream` and `AsyncGenerator`); or, if the object is not async iterable,
* iterable objects (objects such as `Map` and `Set`); or, if the object is not iterable,
* array-like objects (objects with a `length` property and indexed elements).

`Array.fromAsync()` iterates the async iterable in a fashion very similar to `for await...of`. `Array.fromAsync()` is almost equivalent to `Array.from()` in terms of behavior, except the following:

* `Array.fromAsync()` handles async iterable objects.
* `Array.fromAsync()` returns a `Promise` that fulfills to the array instance.
* If `Array.fromAsync()` is called with a non-async iterable object, each element to be added to the array is first awaited.
* If a `mapFn` is provided, its input and output are internally awaited.

`Array.fromAsync()` and `Promise.all()` can both turn an iterable of promises into a promise of an array. However, there are two key differences:

* `Array.fromAsync()` awaits each value yielded from the object sequentially. `Promise.all()` awaits all values concurrently.
* `Array.fromAsync()` iterates the iterable lazily, and doesn't retrieve the next value until the current one is settled. `Promise.all()` retrieves all values in advance and awaits them all.
Examples
--------

### Array from an async iterable

```js
const asyncIterable = (async function\* () {
  for (let i = 0; i < 5; i++) {
    await new Promise((resolve) => setTimeout(resolve, 10 \* i));
    yield i;
  }
})();

Array.fromAsync(asyncIterable).then((array) => console.log(array));
// [0, 1, 2, 3, 4]
```

### Array from a sync iterable

```js
Array.fromAsync(
  new Map([
    [1, 2],
    [3, 4],
  ]),
).then((array) => console.log(array));
// [[1, 2], [3, 4]]
```

### Array from a sync iterable that yields promises

```js
Array.fromAsync(
  new Set([Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)]),
).then((array) => console.log(array));
// [1, 2, 3]
```

### Array from an array-like object of promises

```js
Array.fromAsync({
  length: 3,
  0: Promise.resolve(1),
  1: Promise.resolve(2),
  2: Promise.resolve(3),
}).then((array) => console.log(array));
// [1, 2, 3]
```

### Using mapFn

Both the input and output of `mapFn` are awaited internally by `Array.fromAsync()`.

```js
function delayedValue(v) {
  return new Promise((resolve) => setTimeout(() => resolve(v), 100));
}

Array.fromAsync(
  [delayedValue(1), delayedValue(2), delayedValue(3)],
  (element) => delayedValue(element \* 2),
).then((array) => console.log(array));
// [2, 4, 6]
```

### Comparison with Promise.all()

`Array.fromAsync()` awaits each value yielded from the object sequentially. `Promise.all()` awaits all values concurrently.

```js
function\* makeIterableOfPromises() {
  for (let i = 0; i < 5; i++) {
    yield new Promise((resolve) => setTimeout(resolve, 100));
  }
}

(async () => {
  console.time("Array.fromAsync() time");
  await Array.fromAsync(makeIterableOfPromises());
  console.timeEnd("Array.fromAsync() time");
  // Array.fromAsync() time: 503.610ms

  console.time("Promise.all() time");
  await Promise.all(makeIterableOfPromises());
  console.timeEnd("Promise.all() time");
  // Promise.all() time: 101.728ms
})();
```

### No error handling for sync iterables

Similar to `for await...of`, if the object being iterated is a sync iterable, and an error is thrown while iterating, the `return()` method of the underlying iterator will not be called, so the iterator is not closed.

```js
function\* generatorWithRejectedPromises() {
  try {
    yield 0;
    yield Promise.reject(3);
  } finally {
    console.log("called finally");
  }
}

(async () => {
  try {
    await Array.fromAsync(generatorWithRejectedPromises());
  } catch (e) {
    console.log("caught", e);
  }
})();
// caught 3
// No "called finally" message
```

If you need to close the iterator, you need to use a `for...of` loop instead, and `await` each value yourself.

```js
(async () => {
  const arr = [];
  try {
    for (const val of generatorWithRejectedPromises()) {
      arr.push(await val);
    }
  } catch (e) {
    console.log("caught", e);
  }
})();
// called finally
// caught 3
```

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

| Specification |
| --- |
| ES Array.fromAsync (2022) # sec-array.fromAsync |

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

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

See also
--------

* Polyfill of `Array.fromAsync` in `core-js`
* Indexed collections guide
* `Array`
* `Array()`
* `Array.of()`
* `Array.from()`
* `for await...of`


Array.prototype.reduceRight() - JavaScript

Array.prototype.reduceRight()
=============================

The **`reduceRight()`** method of `Array` instances applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.

See also `Array.prototype.reduce()` for left-to-right.

Try it
------

Syntax
------

```js
reduceRight(callbackFn)
reduceRight(callbackFn, initialValue)
```

### Parameters

`callbackFn`

A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduceRight()`. The function is called with the following arguments:

`accumulator`

The value resulting from the previous call to `callbackFn`. On the first call, its value is `initialValue` if the latter is specified; otherwise its value is the last element of the array.

`currentValue`

The value of the current element. On the first call, its value is the last element if `initialValue` is specified; otherwise its value is the second-to-last element.

`currentIndex`

The index position of `currentValue` in the array. On the first call, its value is `array.length - 1` if `initialValue` is specified, otherwise `array.length - 2`.

`array`

The array `reduceRight()` was called upon.

`initialValue` Optional

Value to use as accumulator to the first call of the `callbackFn`. If no initial value is supplied, the last element in the array will be used and skipped. Calling `reduceRight()` on an empty array without an initial value creates a `TypeError`.

### Return value

The value that results from the reduction.

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

The `reduceRight()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in descending-index order, and accumulates them into a single value. Read the iterative methods section for more information about how these methods work in general.

`callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

Unlike other iterative methods, `reduceRight()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict.

The `reduceRight()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

All caveats about `reduce` discussed in when not to use reduce() apply to `reduceRight` as well. Because JavaScript has no lazy evaluation semantics, there is no performance difference between `reduce` and `reduceRight`.

Examples
--------

### How reduceRight() works without an initial value

The call to the reduceRight `callbackFn` would look something like this:

```js
arr.reduceRight((accumulator, currentValue, index, array) => {
  // …
});
```

The first time the function is called, the `accumulator` and `currentValue` can be one of two values. If an `initialValue` was provided in the call to `reduceRight`, then `accumulator` will be equal to `initialValue` and `currentValue` will be equal to the last value in the array. If no `initialValue` was provided, then `accumulator` will be equal to the last value in the array and `currentValue` will be equal to the second-to-last value.

If the array is empty and no `initialValue` was provided, `TypeError` would be thrown. If the array has only one element (regardless of position) and no `initialValue` was provided, or if `initialValue` is provided but the array is empty, the solo value would be returned without calling `callbackFn`.

Some example run-throughs of the function would look like this:

```js
[0, 1, 2, 3, 4].reduceRight(
  (accumulator, currentValue, index, array) => accumulator + currentValue,
);
```

The callback would be invoked four times, with the arguments and return values in each call being as follows:

|  | `accumulator` | `currentValue` | `index` | Return value |
| --- | --- | --- | --- | --- |
| First call | `4` | `3` | `3` | `7` |
| Second call | `7` | `2` | `2` | `9` |
| Third call | `9` | `1` | `1` | `10` |
| Fourth call | `10` | `0` | `0` | `10` |

The `array` parameter never changes through the process — it's always `[0, 1, 2, 3, 4]`. The value returned by `reduceRight` would be that of the last callback invocation (`10`).

### How reduceRight() works with an initial value

Here we reduce the same array using the same algorithm, but with an `initialValue` of `10` passed as the second argument to `reduceRight()`:

```js
[0, 1, 2, 3, 4].reduceRight(
  (accumulator, currentValue, index, array) => accumulator + currentValue,
  10,
);
```

|  | `accumulator` | `currentValue` | `index` | Return value |
| --- | --- | --- | --- | --- |
| First call | `10` | `4` | `4` | `14` |
| Second call | `14` | `3` | `3` | `17` |
| Third call | `17` | `2` | `2` | `19` |
| Fourth call | `19` | `1` | `1` | `20` |
| Fifth call | `20` | `0` | `0` | `20` |

The value returned by `reduceRight` this time would be, of course, `20`.

### Sum up all values within an array

```js
const sum = [0, 1, 2, 3].reduceRight((a, b) => a + b);
// sum is 6
```

### Run a list of asynchronous functions with callbacks in series each passing their results to the next

```js
const waterfall =
  (...functions) =>
  (callback, ...args) =>
    functions.reduceRight(
      (composition, fn) =>
        (...results) =>
          fn(composition, ...results),
      callback,
    )(...args);

const randInt = (max) => Math.floor(Math.random() \* max);

const add5 = (callback, x) => {
  setTimeout(callback, randInt(1000), x + 5);
};
const mult3 = (callback, x) => {
  setTimeout(callback, randInt(1000), x \* 3);
};
const sub2 = (callback, x) => {
  setTimeout(callback, randInt(1000), x - 2);
};
const split = (callback, x) => {
  setTimeout(callback, randInt(1000), x, x);
};
const add = (callback, x, y) => {
  setTimeout(callback, randInt(1000), x + y);
};
const div4 = (callback, x) => {
  setTimeout(callback, randInt(1000), x / 4);
};

const computation = waterfall(add5, mult3, sub2, split, add, div4);
computation(console.log, 5); // Logs 14

// same as:

const computation2 = (input, callback) => {
  const f6 = (x) => div4(callback, x);
  const f5 = (x, y) => add(f6, x, y);
  const f4 = (x) => split(f5, x);
  const f3 = (x) => sub2(f4, x);
  const f2 = (x) => mult3(f3, x);
  add5(f2, input);
};
```

### Difference between reduce and reduceRight

```js
const a = ["1", "2", "3", "4", "5"];
const left = a.reduce((prev, cur) => prev + cur);
const right = a.reduceRight((prev, cur) => prev + cur);

console.log(left); // "12345"
console.log(right); // "54321"
```

### Defining composable functions

Function composition is a mechanism for combining functions, in which the output of each function is passed into the next one, and the output of the last function is the final result. In this example we use `reduceRight()` to implement function composition.

See also Function composition on Wikipedia.

```js
const compose =
  (...args) =>
  (value) =>
    args.reduceRight((acc, fn) => fn(acc), value);

// Increment passed number
const inc = (n) => n + 1;

// Doubles the passed value
const double = (n) => n \* 2;

// using composition function
console.log(compose(double, inc)(2)); // 6

// using composition function
console.log(compose(inc, double)(2)); // 5
```

### Using reduceRight() with sparse arrays

`reduceRight()` skips missing elements in sparse arrays, but it does not skip `undefined` values.

```js
console.log([1, 2, , 4].reduceRight((a, b) => a + b)); // 7
console.log([1, 2, undefined, 4].reduceRight((a, b) => a + b)); // NaN
```

### Calling reduceRight() on non-array objects

The `reduceRight()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.

```js
const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 4,
  3: 99, // ignored by reduceRight() since length is 3
};
console.log(Array.prototype.reduceRight.call(arrayLike, (x, y) => x - y));
// -1, which is 4 - 3 - 2
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.reduceright |

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

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

See also
--------

* Polyfill of `Array.prototype.reduceRight` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.map()`
* `Array.prototype.flat()`
* `Array.prototype.flatMap()`
* `Array.prototype.reduce()`
* `TypedArray.prototype.reduceRight()`
* `Object.groupBy()`
* `Map.groupBy()`


Array.prototype.join() - JavaScript

Array.prototype.join()
======================

 The **`join()`** method of `Array` instances creates and
 returns a new string by concatenating all of the elements in this array,
 separated by commas or a specified separator string. If the array has
 only one item, then that item will be returned without using the separator.

Try it
------

Syntax
------

```js
join()
join(separator)
```

### Parameters

`separator` Optional

A string to separate each pair of adjacent elements of the array. If omitted, the array elements are separated with a comma (",").

### Return value

A string with all array elements joined. If `array.length` is `0`, the empty string is returned.

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

The string conversions of all array elements are joined into one string. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`.

The `join` method is accessed internally by `Array.prototype.toString()` with no arguments. Overriding `join` of an array instance will override its `toString` behavior as well.

`Array.prototype.join` recursively converts each element, including other arrays, to strings. Because the string returned by `Array.prototype.toString` (which is the same as calling `join()`) does not have delimiters, nested arrays look like they are flattened. You can only control the separator of the first level, while deeper levels always use the default comma.

```js
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

console.log(matrix.join()); // 1,2,3,4,5,6,7,8,9
console.log(matrix.join(";")); // 1,2,3;4,5,6;7,8,9
```

When an array is cyclic (it contains an element that is itself), browsers avoid infinite recursion by ignoring the cyclic reference.

```js
const arr = [];
arr.push(1, [3, arr, 4], 2);
console.log(arr.join(";")); // 1;3,,4;2
```

When used on sparse arrays, the `join()` method iterates empty slots as if they have the value `undefined`.

The `join()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Joining an array four different ways

 The following example creates an array, `a`, with three elements, then joins
 the array four times: using the default separator, then a comma and a space, then a plus
 and an empty string.

```js
const a = ["Wind", "Water", "Fire"];
a.join(); // 'Wind,Water,Fire'
a.join(", "); // 'Wind, Water, Fire'
a.join(" + "); // 'Wind + Water + Fire'
a.join(""); // 'WindWaterFire'
```

### Using join() on sparse arrays

`join()` treats empty slots the same as `undefined` and produces an extra separator:

```js
console.log([1, , 3].join()); // '1,,3'
console.log([1, undefined, 3].join()); // '1,,3'
```

### Calling join() on non-array objects

The `join()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.

```js
const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 4,
  3: 5, // ignored by join() since length is 3
};
console.log(Array.prototype.join.call(arrayLike));
// 2,3,4
console.log(Array.prototype.join.call(arrayLike, "."));
// 2.3.4
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.join |

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

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

See also
--------

* Polyfill of `Array.prototype.join` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.toString()`
* `TypedArray.prototype.join()`
* `String.prototype.split()`


Array.prototype.pop() - JavaScript

Array.prototype.pop()
=====================

 The **`pop()`** method of `Array` instances removes the **last**
 element from an array and returns that element. This method changes the length of the
 array.

Try it
------

Syntax
------

```js
pop()
```

### Parameters

None.

### Return value

The removed element from the array; `undefined` if the array is empty.

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

The `pop()` method removes the last element from an array and returns that value to the caller. If you call `pop()` on an empty array, it returns `undefined`.

`Array.prototype.shift()` has similar behavior to `pop()`, but applied to the first element in an array.

The `pop()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the last element removed, you can use `arr.slice(0, -1)` instead.

The `pop()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

Examples
--------

### Removing the last element of an array

 The following code creates the `myFish` array containing four elements, then
 removes its last element.

```js
const myFish = ["angel", "clown", "mandarin", "sturgeon"];

const popped = myFish.pop();

console.log(myFish); // ['angel', 'clown', 'mandarin' ]

console.log(popped); // 'sturgeon'
```

### Calling pop() on non-array objects

The `pop()` method reads the `length` property of `this`. If the normalized length is 0, `length` is set to `0` again (whereas it may be negative or `undefined` before). Otherwise, the property at `length - 1` is returned and deleted.

```js
const arrayLike = {
  length: 3,
  unrelated: "foo",
  2: 4,
};
console.log(Array.prototype.pop.call(arrayLike));
// 4
console.log(arrayLike);
// { length: 2, unrelated: 'foo' }

const plainObj = {};
// There's no length property, so the length is 0
Array.prototype.pop.call(plainObj);
console.log(plainObj);
// { length: 0 }
```

### Using an object in an array-like fashion

`push` and `pop` are intentionally generic, and we can use that to our advantage — as the following example shows.

Note that in this example, we don't create an array to store a collection of objects. Instead, we store the collection on the object itself and use `call` on `Array.prototype.push` and `Array.prototype.pop` to trick those methods into thinking we're dealing with an array.

```js
const collection = {
  length: 0,
  addElements(...elements) {
    // obj.length will be incremented automatically
    // every time an element is added.

    // Returning what push returns; that is
    // the new value of length property.
    return [].push.call(this, ...elements);
  },
  removeElement() {
    // obj.length will be decremented automatically
    // every time an element is removed.

    // Returning what pop returns; that is
    // the removed element.
    return [].pop.call(this);
  },
};

collection.addElements(10, 20, 30);
console.log(collection.length); // 3
collection.removeElement();
console.log(collection.length); // 2
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.pop |

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

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

See also
--------

* Indexed collections guide
* `Array`
* `Array.prototype.push()`
* `Array.prototype.shift()`
* `Array.prototype.unshift()`
* `Array.prototype.concat()`
* `Array.prototype.splice()`


Array() constructor - JavaScript

Array() constructor
===================

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

Syntax
------

```js
new Array()
new Array(element1)
new Array(element1, element2)
new Array(element1, element2, /\* …, \*/ elementN)
new Array(arrayLength)

Array()
Array(element1)
Array(element1, element2)
Array(element1, element2, /\* …, \*/ elementN)
Array(arrayLength)
```

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

### Parameters

`element1`, …, `elementN`

 A JavaScript array is initialized with the given elements, except in the case where
 a single argument is passed to the `Array` constructor and that argument is
 a number (see the `arrayLength` parameter below). Note that this special case only
 applies to JavaScript arrays created with the `Array` constructor, not
 array literals created with the square bracket syntax.

`arrayLength`

 If the only argument passed to the `Array` constructor is an integer
 between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with
 its `length` property set to that number (**Note:** this
 implies an array of `arrayLength` empty slots, not slots with actual
 `undefined` values — see sparse arrays).

### Exceptions

`RangeError`

Thrown if there's only one argument (`arrayLength`) that is a number, but its value is not an integer or not between 0 and 232 - 1 (inclusive).

Examples
--------

### Array literal notation

 Arrays can be created using the literal
 notation:

```js
const fruits = ["Apple", "Banana"];

console.log(fruits.length); // 2
console.log(fruits[0]); // "Apple"
```

### Array constructor with a single parameter

 Arrays can be created using a constructor with a single number parameter. An array is created with
 its `length` property set to that number, and the array elements are empty
 slots.

```js
const arrayEmpty = new Array(2);

console.log(arrayEmpty.length); // 2
console.log(arrayEmpty[0]); // undefined; actually, it is an empty slot
console.log(0 in arrayEmpty); // false
console.log(1 in arrayEmpty); // false
```

```js
const arrayOfOne = new Array("2"); // Not the number 2 but the string "2"

console.log(arrayOfOne.length); // 1
console.log(arrayOfOne[0]); // "2"
```

### Array constructor with multiple parameters

 If more than one argument is passed to the constructor, a new `Array` with
 the given elements is created.

```js
const fruits = new Array("Apple", "Banana");

console.log(fruits.length); // 2
console.log(fruits[0]); // "Apple"
```

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

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

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

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

See also
--------

* Indexed collections guide
* `Array`


Array.of() - JavaScript

Array.of()
==========

 The **`Array.of()`** static method creates a new `Array`
 instance from a variable number of arguments, regardless of number or type of the
 arguments.

Try it
------

Syntax
------

```js
Array.of()
Array.of(element1)
Array.of(element1, element2)
Array.of(element1, element2, /\* …, \*/ elementN)
```

### Parameters

`element1`, …, `elementN`

Elements used to create the array.

### Return value

A new `Array` instance.

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

The difference between `Array.of()` and the `Array()` constructor is in the handling of single arguments: `Array.of(7)` creates an array with a single element, `7`, whereas `Array(7)` creates an empty array with a `length` property of `7`. (That implies an array of 7 empty slots, not slots with actual `undefined` values.)

```js
Array.of(7); // [7]
Array(7); // array of 7 empty slots

Array.of(1, 2, 3); // [1, 2, 3]
Array(1, 2, 3); // [1, 2, 3]
```

The `Array.of()` method is a generic factory method. For example, if a subclass of `Array` inherits the `of()` method, the inherited `of()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to `of()`. The final `length` will be set again when all elements are assigned. If the `this` value is not a constructor function, the plain `Array` constructor is used instead.

Examples
--------

### Using Array.of()

```js
Array.of(1); // [1]
Array.of(1, 2, 3); // [1, 2, 3]
Array.of(undefined); // [undefined]
```

### Calling of() on non-array constructors

The `of()` method can be called on any constructor function that accepts a single argument representing the length of the new array.

```js
function NotArray(len) {
  console.log("NotArray called with length", len);
}

console.log(Array.of.call(NotArray, 1, 2, 3));
// NotArray called with length 3
// NotArray { '0': 1, '1': 2, '2': 3, length: 3 }

console.log(Array.of.call(Object)); // [Number: 0] { length: 0 }
```

When the `this` value is not a constructor, a plain `Array` object is returned.

```js
console.log(Array.of.call({}, 1)); // [ 1 ]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.of |

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

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

See also
--------

* Polyfill of `Array.of` in `core-js`
* Indexed collections guide
* `Array`
* `Array()`
* `Array.from()`
* `TypedArray.of()`


Array.prototype.copyWithin() - JavaScript

Array.prototype.copyWithin()
============================

The **`copyWithin()`** method of `Array` instances shallow copies part of this array to another location in the same array and returns this array without modifying its length.

Try it
------

Syntax
------

```js
copyWithin(target, start)
copyWithin(target, start, end)
```

### Parameters

`target`

Zero-based index at which to copy the sequence to, converted to an integer. This corresponds to where the element at `start` will be copied to, and all elements between `start` and `end` are copied to succeeding indices.

* Negative index counts back from the end of the array — if `target < 0`, `target + array.length` is used.
* If `target < -array.length`, `0` is used.
* If `target >= array.length`, nothing is copied.
* If `target` is positioned after `start` after normalization, copying only happens until the end of `array.length` (in other words, `copyWithin()` never extends the array).

`start`

Zero-based index at which to start copying elements from, converted to an integer.

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

`end` Optional

Zero-based index at which to end copying elements from, converted to an integer. `copyWithin()` copies up to but not including `end`.

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

### Return value

The modified array.

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

The `copyWithin()` method works like C and C++'s `memmove`, and is a high-performance method to shift the data of an `Array`. This especially applies to the `TypedArray` method of the same name. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap.

Because `undefined` becomes `0` when converted to an integer, omitting the `start` parameter has the same effect as passing `0`, which copies the entire array to the target position, equivalent to a right shift where the right boundary is clipped off and the left boundary is duplicated. This behavior may confuse readers of your code, so you should explicitly pass `0` as `start` instead.

```js
console.log([1, 2, 3, 4, 5].copyWithin(2));
// [1, 2, 1, 2, 3]; move all elements to the right by 2 positions
```

The `copyWithin()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this` and create new properties or delete existing properties, if necessary.

The `copyWithin()` method preserves empty slots. If the region to be copied from is sparse, the empty slots' corresponding new indices are deleted and also become empty slots.

The `copyWithin()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

Examples
--------

### Using copyWithin()

```js
console.log([1, 2, 3, 4, 5].copyWithin(0, 3));
// [4, 5, 3, 4, 5]

console.log([1, 2, 3, 4, 5].copyWithin(0, 3, 4));
// [4, 2, 3, 4, 5]

console.log([1, 2, 3, 4, 5].copyWithin(-2, -3, -1));
// [1, 2, 3, 3, 4]
```

### Using copyWithin() on sparse arrays

`copyWithin()` will propagate empty slots.

```js
console.log([1, , 3].copyWithin(2, 1, 2)); // [1, empty, empty]
```

### Calling copyWithin() on non-array objects

The `copyWithin()` method reads the `length` property of `this` and then manipulates the integer indices involved.

```js
const arrayLike = {
  length: 5,
  3: 1,
};
console.log(Array.prototype.copyWithin.call(arrayLike, 0, 3));
// { '0': 1, '3': 1, length: 5 }
console.log(Array.prototype.copyWithin.call(arrayLike, 3, 1));
// { '0': 1, length: 5 }
// The '3' property is deleted because the copied source is an empty slot
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.copywithin |

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

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

See also
--------

* Polyfill of `Array.prototype.copyWithin` in `core-js`
* Indexed collections guide
* `Array`
* `TypedArray.prototype.copyWithin()`


RangeError() constructor - JavaScript

RangeError() constructor
========================

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

Syntax
------

```js
new RangeError()
new RangeError(message)
new RangeError(message, options)
new RangeError(message, fileName)
new RangeError(message, fileName, lineNumber)

RangeError()
RangeError(message)
RangeError(message, options)
RangeError(message, fileName)
RangeError(message, fileName, lineNumber)
```

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

### Parameters

`message` Optional

Human-readable description of the error.

`options` Optional

An object that has the following properties:

`cause` Optional

 A property indicating the specific cause of the error.
 When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.

`fileName` Optional
Non-standard

The name of the file containing the code that caused the exception

`lineNumber` Optional
Non-standard

The line number of the code that caused the exception

Examples
--------

### Using RangeError (for numeric values)

```js
function check(n) {
  if (!(n >= -500 && n <= 500)) {
    throw new RangeError("The argument must be between -500 and 500.");
  }
}

try {
  check(2000);
} catch (error) {
  if (error instanceof RangeError) {
    // Handle the error
  }
}
```

### Using RangeError (for non-numeric values)

```js
function check(value) {
  if (!["apple", "banana", "carrot"].includes(value)) {
    throw new RangeError(
      'The argument must be an "apple", "banana", or "carrot".',
    );
  }
}

try {
  check("cabbage");
} catch (error) {
  if (error instanceof RangeError) {
    // Handle the error
  }
}
```

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

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

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

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

See also
--------

* `Error`
* `Array`
* `Number.prototype.toExponential()`
* `Number.prototype.toFixed()`
* `Number.prototype.toPrecision()`
* `String.prototype.normalize()`


Generator.prototype.next() - JavaScript

Generator.prototype.next()
==========================

 The **`next()`** method of `Generator` instances returns an
 object with two properties `done` and `value`. You can also
 provide a parameter to the `next` method to send a value to the
 generator.

Syntax
------

```js
next()
next(value)
```

### Parameters

`value` Optional

The value to send to the generator.

 The value will be assigned as a result of a `yield` expression. For
 example, in `variable = yield expression`, the value
 passed to the `.next()` function will be assigned to
 `variable`.

### Return value

An `Object` with two properties:

`done`

A boolean value:

* `true` if the generator is past the end of its control flow. In this case `value` specifies the *return value* of the generator (which may be undefined).
* `false` if the generator is able to produce more values.

`value`

Any JavaScript value yielded or returned by the generator.

Examples
--------

### Using next()

 The following example shows a simple generator and the object that the
 `next` method returns:

```js
function\* gen() {
  yield 1;
  yield 2;
  yield 3;
}

const g = gen(); // Generator { }
g.next(); // { value: 1, done: false }
g.next(); // { value: 2, done: false }
g.next(); // { value: 3, done: false }
g.next(); // { value: undefined, done: true }
```

### Using next() with a list

In this example, `getPage` takes a list and "paginates" it into chunks of size `pageSize`. Each call to `next` will yield one such chunk.

```js
function\* getPage(list, pageSize = 1) {
  for (let index = 0; index < list.length; index += pageSize) {
    yield list.slice(index, index + pageSize);
  }
}

const list = [1, 2, 3, 4, 5, 6, 7, 8];
const page = getPage(list, 3); // Generator { }

page.next(); // { value: [1, 2, 3], done: false }
page.next(); // { value: [4, 5, 6], done: false }
page.next(); // { value: [7, 8], done: false }
page.next(); // { value: undefined, done: true }
```

### Sending values to the generator

In this example, `next` is called with a value.

**Note:** The first call does not log anything, because the generator was not yielding anything initially.

```js
function\* gen() {
  while (true) {
    const value = yield;
    console.log(value);
  }
}

const g = gen();
g.next(1); // Returns { value: undefined, done: false }
// No log at this step: the first value sent through `next` is lost
g.next(2); // Returns { value: undefined, done: false }
// Logs 2
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-generator.prototype.next |

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

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

See also
--------

* `function*`
* Iterators and generators guide


Generator.prototype.throw() - JavaScript

Generator.prototype.throw()
===========================

The **`throw()`** method of `Generator` instances acts as if a `throw` statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself.

Syntax
------

```js
generatorInstance.throw(exception)
```

### Parameters

`exception`

The exception to throw. For debugging purposes, it is useful to make it an `instanceof` `Error`.

### Return value

If the thrown exception is caught by a `try...catch` and the generator resumes to yield more values, it will return an `Object` with two properties:

`done`

A boolean value:

* `true` if the generator function's control flow has reached the end.
* `false` if the generator function is able to produce more values.

`value`

The value yielded from the next `yield` expression.

### Exceptions

If the thrown exception is not caught by a `try...catch`, the `exception` passed to `throw()` will be thrown out from the generator function.

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

The `throw()` method, when called, can be seen as if a `throw exception;` statement is inserted in the generator's body at the current suspended position, where `exception` is the exception passed to the `throw()` method. Therefore, in a typical flow, calling `throw(exception)` will cause the generator to throw. However, if the `yield` expression is wrapped in a `try...catch` block, the error may be caught and control flow can either resume after error handling, or exit gracefully.

Examples
--------

### Using throw()

The following example shows a simple generator and an error that is thrown using the `throw` method. An error can be caught by a `try...catch` block as usual.

```js
function\* gen() {
  while (true) {
    try {
      yield 42;
    } catch (e) {
      console.log("Error caught!");
    }
  }
}

const g = gen();
g.next();
// { value: 42, done: false }
g.throw(new Error("Something went wrong"));
// "Error caught!"
// { value: 42, done: false }
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-generator.prototype.throw |

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

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

See also
--------

* `function*`


Generator.prototype.return() - JavaScript

Generator.prototype.return()
============================

The **`return()`** method of `Generator` instances acts as if a `return` statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a `try...finally` block.

Syntax
------

```js
generatorInstance.return()
generatorInstance.return(value)
```

### Parameters

`value` Optional

The value to return.

### Return value

An `Object` with two properties:

`done`

A boolean value:

* `true` if the generator function's control flow has reached the end.
* `false` if the generator function's control flow hasn't reached the end and can produce more values. This can only happen if the `return` is captured in a `try...finally` and there are more `yield` expressions in the `finally` block.

`value`

The value that is given as an argument, or, if the `yield` expression is wrapped in a `try...finally`, the value yielded/returned from the `finally` block.

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

The `return()` method, when called, can be seen as if a `return value;` statement is inserted in the generator's body at the current suspended position, where `value` is the value passed to the `return()` method. Therefore, in a typical flow, calling `return(value)` will return `{ done: true, value: value }`. However, if the `yield` expression is wrapped in a `try...finally` block, the control flow doesn't exit the function body, but proceeds to the `finally` block instead. In this case, the value returned may be different, and `done` may even be `false`, if there are more `yield` expressions within the `finally` block.

Examples
--------

### Using return()

The following example shows a simple generator and the `return` method.

```js
function\* gen() {
  yield 1;
  yield 2;
  yield 3;
}

const g = gen();

g.next(); // { value: 1, done: false }
g.return("foo"); // { value: "foo", done: true }
g.next(); // { value: undefined, done: true }
```

If `return(value)` is called on a generator that is already in "completed" state, the generator will remain in "completed" state.

If no argument is provided, the `value` property of the returned object will be `undefined`. If an argument is provided, it will become the value of the `value` property of the returned object, unless the `yield` expression is wrapped in a `try...finally`.

```js
function\* gen() {
  yield 1;
  yield 2;
  yield 3;
}

const g = gen();
g.next(); // { value: 1, done: false }
g.next(); // { value: 2, done: false }
g.next(); // { value: 3, done: false }
g.next(); // { value: undefined, done: true }
g.return(); // { value: undefined, done: true }
g.return(1); // { value: 1, done: true }
```

### Using return() with try...finally

The fact that the `return` method has been called can only be made known to the generator itself if the `yield` expression is wrapped in a `try...finally` block.

When the `return` method is called on a generator that is suspended within a `try` block, execution in the generator proceeds to the `finally` block — since the `finally` block of `try...finally` statements always executes.

```js
function\* gen() {
  yield 1;
  try {
    yield 2;
    yield 3;
  } finally {
    yield "cleanup";
  }
}

const g1 = gen();
g1.next(); // { value: 1, done: false }

// Execution is suspended before the try...finally.
g1.return("early return"); // { value: 'early return', done: true }

const g2 = gen();
g2.next(); // { value: 1, done: false }
g2.next(); // { value: 2, done: false }

// Execution is suspended within the try...finally.
g2.return("early return"); // { value: 'cleanup', done: false }

// The completion value is preserved
g2.next(); // { value: 'early return', done: true }

// Generator is in the completed state
g2.return("not so early return"); // { value: 'not so early return', done: true }
```

The return value of the finally block can also become the `value` of the result returned from the `return` call.

```js
function\* gen() {
  try {
    yield 1;
  } finally {
    return "cleanup";
  }
}

const g1 = gen();
g1.next(); // { value: 1, done: false }
g1.return("early return"); // { value: 'cleanup', done: true }
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-generator.prototype.return |

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

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

See also
--------

* `function*`


Reflect.getPrototypeOf() - JavaScript

Reflect.getPrototypeOf()
========================

The **`Reflect.getPrototypeOf()`** static method is like `Object.getPrototypeOf()`. It returns the prototype of the specified object.

Try it
------

Syntax
------

```js
Reflect.getPrototypeOf(target)
```

### Parameters

`target`

The target object of which to get the prototype.

### Return value

The prototype of the given object, which may be an object or `null`.

### Exceptions

`TypeError`

Thrown if `target` is not an object.

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

`Reflect.getPrototypeOf()` provides the reflective semantic of retrieving the prototype of an object. The only difference with `Object.getPrototypeOf()` is how non-object targets are handled. `Reflect.getPrototypeOf()` throws a `TypeError` if the target is not an object, while `Object.getPrototypeOf()` coerces it to an object.

`Reflect.getPrototypeOf()` invokes the `[[GetPrototypeOf]]` object internal method of `target`.

Examples
--------

### Using Reflect.getPrototypeOf()

```js
Reflect.getPrototypeOf({}); // Object.prototype
Reflect.getPrototypeOf(Object.prototype); // null
Reflect.getPrototypeOf(Object.create(null)); // null
```

### Difference with Object.getPrototypeOf()

```js
// Same result for Objects
Object.getPrototypeOf({}); // Object.prototype
Reflect.getPrototypeOf({}); // Object.prototype

// Both throw in ES5 for non-Objects
Object.getPrototypeOf("foo"); // Throws TypeError
Reflect.getPrototypeOf("foo"); // Throws TypeError

// In ES2015 only Reflect throws, Object coerces non-Objects
Object.getPrototypeOf("foo"); // String.prototype
Reflect.getPrototypeOf("foo"); // Throws TypeError

// To mimic the Object ES2015 behavior you need to coerce
Reflect.getPrototypeOf(Object("foo")); // String.prototype
```

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

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

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

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

See also
--------

* Polyfill of `Reflect.getPrototypeOf` in `core-js`
* `Reflect`
* `Object.getPrototypeOf()`
* `handler.getPrototypeOf()`


Reflect.deleteProperty() - JavaScript

Reflect.deleteProperty()
========================

The **`Reflect.deleteProperty()`** static method is like the `delete` operator, but as a function. It deletes a property from an object.

Try it
------

Syntax
------

```js
Reflect.deleteProperty(target, propertyKey)
```

### Parameters

`target`

The target object on which to delete the property.

`propertyKey`

The name of the property to be deleted.

### Return value

A boolean indicating whether or not the property was successfully deleted.

### Exceptions

`TypeError`

Thrown if `target` is not an object.

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

`Reflect.deleteProperty()` provides the reflective semantic of the `delete` operator. That is, `Reflect.deleteProperty(target, propertyKey)` is semantically equivalent to:

```js
delete target.propertyKey;
```

At the very low level, deleting a property returns a boolean (as is the case with the proxy handler). `Reflect.deleteProperty()` directly returns the status, while `delete` would throw a `TypeError` in strict mode if the status is `false`. In non-strict mode, `delete` and `Reflect.deleteProperty()` have the same behavior.

`Reflect.deleteProperty()` invokes the `[[Delete]]` object internal method of `target`.

Examples
--------

### Using Reflect.deleteProperty()

```js
const obj = { x: 1, y: 2 };
Reflect.deleteProperty(obj, "x"); // true
console.log(obj); // { y: 2 }

const arr = [1, 2, 3, 4, 5];
Reflect.deleteProperty(arr, "3"); // true
console.log(arr); // [1, 2, 3, undefined, 5]

// Returns true if no such property exists
Reflect.deleteProperty({}, "foo"); // true

// Returns false if a property is unconfigurable
Reflect.deleteProperty(Object.freeze({ foo: 1 }), "foo"); // false
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-reflect.deleteproperty |

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

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

See also
--------

* Polyfill of `Reflect.deleteProperty` in `core-js`
* `Reflect`
* `delete`
* `handler.deleteProperty()`


Reflect.apply() - JavaScript

Reflect.apply()
===============

The **`Reflect.apply()`** static method calls a target function with arguments as specified.

Try it
------

Syntax
------

```js
Reflect.apply(target, thisArgument, argumentsList)
```

### Parameters

`target`

The target function to call.

`thisArgument`

The value of `this` provided for the call to `target`.

`argumentsList`

An array-like object specifying the arguments with which `target` should be called.

### Return value

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

### Exceptions

`TypeError`

Thrown if `target` is not a function or `argumentsList` is not an object.

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

`Reflect.apply()` provides the reflective semantic of a function call. That is, `Reflect.apply(target, thisArgument, argumentsList)` is semantically equivalent to:

```js
Math.floor.apply(null, [1.75]);
Reflect.apply(Math.floor, null, [1.75]);
```

The only differences are:

* `Reflect.apply()` takes the function to call as the `target` parameter instead of the `this` context.
* `Reflect.apply()` throws if `argumentsList` is omitted instead of defaulting to calling with no parameters.

`Reflect.apply()` invokes the `[[Call]]` object internal method of `target`.

Examples
--------

### Using Reflect.apply()

```js
Reflect.apply(Math.floor, undefined, [1.75]);
// 1;

Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]);
// "hello"

Reflect.apply(RegExp.prototype.exec, /ab/, ["confabulation"]).index;
// 4

Reflect.apply("".charAt, "ponies", [3]);
// "i"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-reflect.apply |

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

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

See also
--------

* Polyfill of `Reflect.apply` in `core-js`
* `Reflect`
* `Function.prototype.apply()`
* `handler.apply()`


Reflect.construct() - JavaScript

Reflect.construct()
===================

The **`Reflect.construct()`** static method is like the `new` operator, but as a function. It is equivalent to calling `new target(...args)`. It gives also the added option to specify a different `new.target` value.

Try it
------

Syntax
------

```js
Reflect.construct(target, argumentsList)
Reflect.construct(target, argumentsList, newTarget)
```

### Parameters

`target`

The target function to call.

`argumentsList`

An array-like object specifying the arguments with which `target` should be called.

`newTarget` Optional

The value of `new.target` operator, which usually specifies the prototype of the returned object. If `newTarget` is not present, its value defaults to `target`.

### Return value

A new instance of `target` (or `newTarget`, if present), initialized by `target` as a constructor with the given `argumentsList`.

### Exceptions

`TypeError`

Thrown if `target` or `newTarget` is not a constructor, or if `argumentsList` is not an object.

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

`Reflect.apply()` provides the reflective semantic of a constructor call. That is, `Reflect.construct(target, argumentsList, newTarget)` is semantically equivalent to:

```js
new target(...argumentsList);
```

Note that when using the `new` operator, `target` and `newTarget` are always the same constructor — but `Reflect.construct()` allows you to pass a different `new.target` value. Conceptually, `newTarget` is the function on which `new` was called, and `newTarget.prototype` will become the constructed object's prototype, while `target` is the constructor that is actually executed to initialize the object. For example, `new.target` may also be different from the currently executed constructor in class inheritance.

```js
class A {
  constructor() {
    console.log(new.target.name);
  }
}
class B extends A {}

new B(); // "B"
```

`Reflect.construct()` allows you to invoke a constructor with a variable number of arguments. (This is also possible with the spread syntax in a normal constructor call.)

```js
const obj = new Foo(...args);
const obj = Reflect.construct(Foo, args);
```

`Reflect.construct()` invokes the `[[Construct]]` object internal method of `target`.

Examples
--------

### Using Reflect.construct()

```js
const d = Reflect.construct(Date, [1776, 6, 4]);
d instanceof Date; // true
d.getFullYear(); // 1776
```

### Reflect.construct() vs. Object.create()

Prior to the introduction of `Reflect`, objects could be constructed using an arbitrary combination of constructors and prototypes using `Object.create()`.

```js
function OneClass() {
  this.name = "one";
}

function OtherClass() {
  this.name = "other";
}

const obj2 = Object.create(OtherClass.prototype);
OneClass.apply(obj2, args);

console.log(obj1.name); // 'one'
console.log(obj2.name); // 'one'

console.log(obj1 instanceof OneClass); // false
console.log(obj2 instanceof OneClass); // false

console.log(obj1 instanceof OtherClass); // true
console.log(obj2 instanceof OtherClass); // true

// Another example to demonstrate below:

function func1(a, b, c, d) {
  console.log(arguments[3]);
}

function func2(d, e, f, g) {
  console.log(arguments[3]);
}

const obj1 = Reflect.construct(func1, ["I", "Love", "my", "country"]);
```

However, while the end result is the same, there is one important difference in the process. When using `Object.create()` and `Function.prototype.apply()`, the `new.target` operator will point to `undefined` within the function used as the constructor, since the `new` keyword is not being used to create the object. (In fact, it uses the `apply` semantic, not `construct`, although normal functions happen to operate nearly the same.)

When invoking `Reflect.construct()`, on the other hand, the `new.target` operator will point to the `newTarget` parameter if supplied, or `target` if not.

```js
function OneClass() {
  console.log("OneClass");
  console.log(new.target);
}
function OtherClass() {
  console.log("OtherClass");
  console.log(new.target);
}

const obj1 = Reflect.construct(OneClass, args);
// Logs:
// OneClass
// function OneClass { ... }

const obj2 = Reflect.construct(OneClass, args, OtherClass);
// Logs:
// OneClass
// function OtherClass { ... }

const obj3 = Object.create(OtherClass.prototype);
OneClass.apply(obj3, args);
// Output:
// OneClass
// undefined
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-reflect.construct |

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

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

See also
--------

* Polyfill of `Reflect.construct` in `core-js`
* `Reflect`
* `new`
* `new.target`
* `handler.construct()`


Reflect.ownKeys() - JavaScript

Reflect.ownKeys()
=================

The **`Reflect.ownKeys()`** static method returns an array of the `target` object's own property keys.

Try it
------

Syntax
------

```js
Reflect.ownKeys(target)
```

### Parameters

`target`

The target object from which to get the own keys.

### Return value

An `Array` of the `target` object's own property keys, including strings and symbols. For most objects, the array will be in the order of:

1. Non-negative integer indexes in increasing numeric order (but as strings)
2. Other string keys in the order of property creation
3. Symbol keys in the order of property creation.
### Exceptions

`TypeError`

Thrown if `target` is not an object.

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

`Reflect.ownKeys()` provides the reflective semantic of retrieving all property keys of an object. It is the only way to get all own properties – enumerable and not enumerable, strings and symbols — in one call, without extra filtering logic. For example, `Object.getOwnPropertyNames()` takes the return value of `Reflect.ownKeys()` and filters to only string values, while `Object.getOwnPropertySymbols()` filters to only symbol values. Because normal objects implement `[[OwnPropertyKeys]]` to return all string keys before symbol keys, `Reflect.ownKeys(target)` is usually equivalent to `Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))`. However, if the object has a custom `[[OwnPropertyKeys]]` method (such as through a proxy's `ownKeys` handler), the order of the keys may be different.

`Reflect.ownKeys()` invokes the `[[OwnPropertyKeys]]` object internal method of `target`.

Examples
--------

### Using Reflect.ownKeys()

```js
Reflect.ownKeys({ z: 3, y: 2, x: 1 }); // [ "z", "y", "x" ]
Reflect.ownKeys([]); // ["length"]

const sym = Symbol.for("comet");
const sym2 = Symbol.for("meteor");
const obj = {
  [sym]: 0,
  str: 0,
  773: 0,
  0: 0,
  [sym2]: 0,
  "-1": 0,
  8: 0,
  "second str": 0,
};
Reflect.ownKeys(obj);
// [ "0", "8", "773", "str", "-1", "second str", Symbol(comet), Symbol(meteor) ]
// Indexes in numeric order,
// strings in insertion order,
// symbols in insertion order
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-reflect.ownkeys |

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

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

See also
--------

* Polyfill of `Reflect.ownKeys` in `core-js`
* `Reflect`
* `Object.getOwnPropertyNames()`
* `Object.getOwnPropertySymbols()`
* `handler.ownKeys()`


Reflect.set() - JavaScript

Reflect.set()
=============

The **`Reflect.set()`** static method is like the property accessor and assignment syntax, but as a function.

Try it
------

Syntax
------

```js
Reflect.set(target, propertyKey, value)
Reflect.set(target, propertyKey, value, receiver)
```

### Parameters

`target`

The target object on which to set the property.

`propertyKey`

The name of the property to set.

`value`

The value to set.

`receiver` Optional

The value of `this` provided for the call to the setter for `propertyKey` on `target`. If provided and `target` does not have a setter for `propertyKey`, the property will be set on `receiver` instead.

### Return value

A `Boolean` indicating whether or not setting the property was successful.

### Exceptions

`TypeError`

Thrown if `target` is not an object.

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

`Reflect.set()` provides the reflective semantic of a property access. That is, `Reflect.set(target, propertyKey, value, receiver)` is semantically equivalent to:

```js
target[propertyKey] = value;
```

Note that in a normal property access, `target` and `receiver` would observably be the same object.

`Reflect.set()` invokes the `[[Set]]` object internal method of `target`.

Examples
--------

### Using Reflect.set()

```js
// Object
const obj = {};
Reflect.set(obj, "prop", "value"); // true
obj.prop; // "value"

// Array
const arr = ["duck", "duck", "duck"];
Reflect.set(arr, 2, "goose"); // true
arr[2]; // "goose"

// It can truncate an array.
Reflect.set(arr, "length", 1); // true
arr; // ["duck"]

// With just one argument, propertyKey and value are "undefined".
Reflect.set(obj); // true
Reflect.getOwnPropertyDescriptor(obj, "undefined");
// { value: undefined, writable: true, enumerable: true, configurable: true }
```

### Different target and receiver

When the `target` and `receiver` are different, `Reflect.set` will use the property descriptor of `target` (to find the setter or determine if the property is writable), but set the property on `receiver`.

```js
const target = {};
const receiver = {};
Reflect.set(target, "a", 2, receiver); // true
// target is {}; receiver is { a: 2 }

const target = { a: 1 };
const receiver = {};
Reflect.set(target, "a", 2, receiver); // true
// target is { a: 1 }; receiver is { a: 2 }

const target = {
  set a(v) {
    this.b = v;
  },
};
const receiver = {};
Reflect.set(target, "a", 2, receiver); // true
// target is { a: [Setter] }; receiver is { b: 2 }
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-reflect.set |

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

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

See also
--------

* Polyfill of `Reflect.set` in `core-js`
* `Reflect`
* Property accessors
* `handler.set()`


Reflect.defineProperty() - JavaScript

Reflect.defineProperty()
========================

The **`Reflect.defineProperty()`** static method is like `Object.defineProperty()` but returns a `Boolean`.

Try it
------

Syntax
------

```js
Reflect.defineProperty(target, propertyKey, attributes)
```

### Parameters

`target`

The target object on which to define the property.

`propertyKey`

The name of the property to be defined or modified.

`attributes`

The attributes for the property being defined or modified.

### Return value

A boolean indicating whether or not the property was successfully defined.

### Exceptions

`TypeError`

Thrown if `target` or `attributes` is not an object.

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

`Reflect.defineProperty()` provides the reflective semantic of defining an own property on an object. At the very low level, defining a property returns a boolean (as is the case with the proxy handler). `Object.defineProperty()` provides nearly the same semantic, but it throws a `TypeError` if the status is `false` (the operation was unsuccessful), while `Reflect.defineProperty()` directly returns the status.

Many built-in operations would also define own properties on objects. The most significant difference between defining properties and setting them is that setters aren't invoked. For example, class fields directly define properties on the instance without invoking setters.

```js
class B extends class A {
  set a(v) {
    console.log("Setter called");
  }
} {
  a = 1; // Nothing logged
}
```

`Reflect.defineProperty()` invokes the `[[DefineOwnProperty]]` object internal method of `target`.

Examples
--------

### Using Reflect.defineProperty()

```js
const obj = {};
Reflect.defineProperty(obj, "x", { value: 7 }); // true
console.log(obj.x); // 7
```

### Checking if property definition has been successful

With `Object.defineProperty()`, which returns an object if successful, or throws a `TypeError` otherwise, you would use a `try...catch` block to catch any error that occurred while defining a property.

Because `Reflect.defineProperty()` returns a Boolean success status, you can just use an `if...else` block here:

```js
if (Reflect.defineProperty(target, property, attributes)) {
  // success
} else {
  // failure
}
```

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

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

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

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

See also
--------

* Polyfill of `Reflect.defineProperty` in `core-js`
* `Reflect`
* `Object.defineProperty()`
* `handler.defineProperty()`


Reflect.getOwnPropertyDescriptor() - JavaScript

Reflect.getOwnPropertyDescriptor()
==================================

The **`Reflect.getOwnPropertyDescriptor()`** static method is like `Object.getOwnPropertyDescriptor()`. It returns a property descriptor of the given property if it exists on the object, `undefined` otherwise.

Try it
------

Syntax
------

```js
Reflect.getOwnPropertyDescriptor(target, propertyKey)
```

### Parameters

`target`

The target object in which to look for the property.

`propertyKey`

The name of the property to get an own property descriptor for.

### Return value

A property descriptor object if the property exists as an own property of `target`; otherwise, `undefined`.

### Exceptions

`TypeError`

Thrown if `target` is not an object.

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

`Reflect.getOwnPropertyDescriptor()` provides the reflective semantic of retrieving the property descriptor of an object. The only difference with `Object.getOwnPropertyDescriptor()` is how non-object targets are handled. `Reflect.getOwnPropertyDescriptor()` throws a `TypeError` if the target is not an object, while `Object.getOwnPropertyDescriptor()` coerces it to an object.

`Reflect.getOwnPropertyDescriptor()` invokes the `[[GetOwnProperty]]` object internal method of `target`.

Examples
--------

### Using Reflect.getOwnPropertyDescriptor()

```js
Reflect.getOwnPropertyDescriptor({ x: "hello" }, "x");
// {value: "hello", writable: true, enumerable: true, configurable: true}

Reflect.getOwnPropertyDescriptor({ x: "hello" }, "y");
// undefined

Reflect.getOwnPropertyDescriptor([], "length");
// {value: 0, writable: true, enumerable: false, configurable: false}
```

### Difference with Object.getOwnPropertyDescriptor()

If the `target` argument to this method is not an object (a primitive), then it will cause a `TypeError`. With `Object.getOwnPropertyDescriptor`, a non-object first argument will be coerced to an object at first.

```js
Reflect.getOwnPropertyDescriptor("foo", 0);
// TypeError: "foo" is not non-null object

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

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

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

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

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

See also
--------

* Polyfill of `Reflect.getOwnPropertyDescriptor` in `core-js`
* `Reflect`
* `Object.getOwnPropertyDescriptor()`
* `handler.getOwnPropertyDescriptor()`


Reflect.setPrototypeOf() - JavaScript

Reflect.setPrototypeOf()
========================

The **`Reflect.setPrototypeOf()`** static method is like `Object.setPrototypeOf()` but returns a `Boolean`. It sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object.

Try it
------

Syntax
------

```js
Reflect.setPrototypeOf(target, prototype)
```

### Parameters

`target`

The target object of which to set the prototype.

`prototype`

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

### Return value

A `Boolean` indicating whether or not the prototype was successfully set.

### Exceptions

`TypeError`

Thrown if `target` is not an object or if `prototype` is neither an object nor `null`.

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

`Reflect.setPrototypeOf()` provides the reflective semantic of setting the prototype of an object. At the very low level, setting the prototype returns a boolean (as is the case with the proxy handler). `Object.setPrototypeOf()` provides nearly the same semantic, but it throws a `TypeError` if the status is `false` (the operation was unsuccessful), while `Reflect.setPrototypeOf()` directly returns the status.

`Reflect.setPrototypeOf()` invokes the `[[SetPrototypeOf]]` object internal method of `target`.

Examples
--------

### Using Reflect.setPrototypeOf()

```js
Reflect.setPrototypeOf({}, Object.prototype); // true

// It can change an object's [[Prototype]] to null.
Reflect.setPrototypeOf({}, null); // true

// Returns false if target is not extensible.
Reflect.setPrototypeOf(Object.freeze({}), null); // false

// Returns false if it cause a prototype chain cycle.
const target = {};
const proto = Object.create(target);
Reflect.setPrototypeOf(target, proto); // false
```

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

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

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

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

See also
--------

* Polyfill of `Reflect.setPrototypeOf` in `core-js`
* `Reflect`
* `Object.setPrototypeOf()`
* `handler.setPrototypeOf()`


Reflect.has() - JavaScript

Reflect.has()
=============

 The **`Reflect.has()`** static method is like the `in` operator, but
 as a function.

Try it
------

Syntax
------

```js
Reflect.has(target, propertyKey)
```

### Parameters

`target`

The target object in which to look for the property.

`propertyKey`

The name of the property to check.

### Return value

A `Boolean` indicating whether or not the `target` has the property.

### Exceptions

`TypeError`

Thrown if `target` is not an object.

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

`Reflect.has()` provides the reflective semantic of checking if a property is in an object. That is, `Reflect.has(target, propertyKey)` is semantically equivalent to:

```js
propertyKey in target;
```

`Reflect.has()` invokes the `[[HasProperty]]` object internal method of `target`.

Examples
--------

### Using Reflect.has()

```js
Reflect.has({ x: 0 }, "x"); // true
Reflect.has({ x: 0 }, "y"); // false

// returns true for properties in the prototype chain
Reflect.has({ x: 0 }, "toString");

// Proxy with .has() handler method
obj = new Proxy(
  {},
  {
    has(t, k) {
      return k.startsWith("door");
    },
  },
);
Reflect.has(obj, "doorbell"); // true
Reflect.has(obj, "dormitory"); // false
```

`Reflect.has` returns `true` for any inherited properties, like the `in` operator:

```js
const a = { foo: 123 };
const b = { \_\_proto\_\_: a };
const c = { \_\_proto\_\_: b };
// The prototype chain is: c -> b -> a
Reflect.has(c, "foo"); // true
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-reflect.has |

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

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

See also
--------

* Polyfill of `Reflect.has` in `core-js`
* `Reflect`
* `in`
* `handler.has()`


Reflect.get() - JavaScript

Reflect.get()
=============

The **`Reflect.get()`** static method is like the property accessor syntax, but as a function.

Try it
------

Syntax
------

```js
Reflect.get(target, propertyKey)
Reflect.get(target, propertyKey, receiver)
```

### Parameters

`target`

The target object on which to get the property.

`propertyKey`

The name of the property to get.

`receiver` Optional

The value of `this` provided for the call to `target` if a getter is encountered.

### Return value

The value of the property.

### Exceptions

`TypeError`

Thrown if `target` is not an object.

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

`Reflect.get()` provides the reflective semantic of a property access. That is, `Reflect.get(target, propertyKey, receiver)` is semantically equivalent to:

```js
target[propertyKey];
```

Note that in a normal property access, `target` and `receiver` would observably be the same object.

`Reflect.get()` invokes the `[[Get]]` object internal method of `target`.

Examples
--------

### Using Reflect.get()

```js
// Object
const obj1 = { x: 1, y: 2 };
Reflect.get(obj1, "x"); // 1

// Array
Reflect.get(["zero", "one"], 1); // "one"

// Proxy with a get handler
const obj2 = new Proxy(
  { p: 1 },
  {
    get(t, k, r) {
      return k + "bar";
    },
  },
);
Reflect.get(obj2, "foo"); // "foobar"

// Proxy with get handler and receiver
const obj3 = new Proxy(
  { p: 1, foo: 2 },
  {
    get(t, prop, receiver) {
      return receiver[prop] + "bar";
    },
  },
);
Reflect.get(obj3, "foo", { foo: 3 }); // "3bar"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-reflect.get |

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

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

See also
--------

* Polyfill of `Reflect.get` in `core-js`
* `Reflect`
* Property accessors
* `handler.get()`


Reflect.isExtensible() - JavaScript

Reflect.isExtensible()
======================

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

Try it
------

Syntax
------

```js
Reflect.isExtensible(target)
```

### Parameters

`target`

The target object which to check if it is extensible.

### Return value

A `Boolean` indicating whether or not the target is extensible.

### Exceptions

`TypeError`

Thrown if `target` is not an object.

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

`Reflect.isExtensible()` provides the reflective semantic of checking if an object is extensible. The only difference with `Object.isExtensible()` is how non-object targets are handled. `Reflect.isExtensible()` throws a `TypeError` if the target is not an object, while `Object.isExtensible()` always returns `false` for non-object targets.

`Reflect.isExtensible()` invokes the `[[IsExtensible]]` object internal method of `target`.

Examples
--------

### Using Reflect.isExtensible()

See also `Object.isExtensible()`.

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

// ...but that can be changed.
Reflect.preventExtensions(empty);
Reflect.isExtensible(empty); // false

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

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

### Difference with Object.isExtensible()

If the `target` argument to this method is not an object (a primitive), then it will cause a `TypeError`. With `Object.isExtensible()`, a non-object `target` will return false without any errors.

```js
Reflect.isExtensible(1);
// TypeError: 1 is not an object

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

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

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

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

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

See also
--------

* Polyfill of `Reflect.isExtensible` in `core-js`
* `Reflect`
* `Object.isExtensible()`
* `handler.isExtensible()`


Reflect.preventExtensions() - JavaScript

Reflect.preventExtensions()
===========================

The **`Reflect.preventExtensions()`** static method is like `Object.preventExtensions()`. It prevents new properties from ever being added to an object (i.e., prevents future extensions to the object).

Try it
------

Syntax
------

```js
Reflect.preventExtensions(target)
```

### Parameters

`target`

The target object on which to prevent extensions.

### Return value

A `Boolean` indicating whether or not the target was successfully set to prevent extensions.

### Exceptions

`TypeError`

Thrown if `target` is not an object.

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

`Reflect.preventExtensions()` provides the reflective semantic of preventing extensions of an object. The differences with `Object.preventExtensions()` are:

* `Reflect.preventExtensions()` throws a `TypeError` if the target is not an object, while `Object.preventExtensions()` always returns non-object targets as-is.
* `Reflect.preventExtensions()` returns a `Boolean` indicating whether or not the target was successfully set to prevent extensions, while `Object.preventExtensions()` returns the target object.

`Reflect.preventExtensions()` invokes the `[[PreventExtensions]]` object internal method of `target`.

Examples
--------

### Using Reflect.preventExtensions()

See also `Object.preventExtensions()`.

```js
// Objects are extensible by default.
const empty = {};
Reflect.isExtensible(empty); // true

// ...but that can be changed.
Reflect.preventExtensions(empty);
Reflect.isExtensible(empty); // false
```

### Difference with Object.preventExtensions()

If the `target` argument to this method is not an object (a primitive), then it will cause a `TypeError`. With `Object.preventExtensions()`, a non-object `target` will be returned as-is without any errors.

```js
Reflect.preventExtensions(1);
// TypeError: 1 is not an object

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

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

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

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

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

See also
--------

* Polyfill of `Reflect.preventExtensions` in `core-js`
* `Reflect`
* `Object.preventExtensions()`
* `handler.preventExtensions()`