repo_id
stringlengths 22
103
| file_path
stringlengths 41
147
| content
stringlengths 181
193k
| __index_level_0__
int64 0
0
|
---|---|---|---|
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics | data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics/exchange/index.md | ---
title: Atomics.exchange()
slug: Web/JavaScript/Reference/Global_Objects/Atomics/exchange
page-type: javascript-static-method
browser-compat: javascript.builtins.Atomics.exchange
---
{{JSRef}}
The **`Atomics.exchange()`** static method exchanges a given value at a given position in the array and returns the old value at that position. This atomic operation guarantees that no other write happens between the read of the old value and the write of the new value.
{{EmbedInteractiveExample("pages/js/atomics-exchange.html")}}
## Syntax
```js-nolint
Atomics.exchange(typedArray, index, value)
```
### Parameters
- `typedArray`
- : An integer typed array. One of {{jsxref("Int8Array")}}, {{jsxref("Uint8Array")}}, {{jsxref("Int16Array")}}, {{jsxref("Uint16Array")}}, {{jsxref("Int32Array")}}, {{jsxref("Uint32Array")}}, {{jsxref("BigInt64Array")}}, or {{jsxref("BigUint64Array")}}.
- `index`
- : The position in the `typedArray` to exchange a `value`.
- `value`
- : The number to exchange.
### Return value
The old value at the given position (`typedArray[index]`).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `typedArray` is not one of the allowed integer types.
- {{jsxref("RangeError")}}
- : Thrown if `index` is out of bounds in the `typedArray`.
## Examples
### Using exchange()
```js
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
Atomics.exchange(ta, 0, 12); // returns 0, the old value
Atomics.load(ta, 0); // 12
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Atomics")}}
- {{jsxref("Atomics.compareExchange()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics | data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics/notify/index.md | ---
title: Atomics.notify()
slug: Web/JavaScript/Reference/Global_Objects/Atomics/notify
page-type: javascript-static-method
browser-compat: javascript.builtins.Atomics.notify
---
{{JSRef}}
The **`Atomics.notify()`** static
method notifies up some agents that are sleeping in the wait queue.
> **Note:** This operation only works with an {{jsxref("Int32Array")}} or {{jsxref("BigInt64Array")}} that views a {{jsxref("SharedArrayBuffer")}}.
> It will return `0` on non-shared `ArrayBuffer` objects.
## Syntax
```js-nolint
Atomics.notify(typedArray, index, count)
```
### Parameters
- `typedArray`
- : An {{jsxref("Int32Array")}} or {{jsxref("BigInt64Array")}} that views a {{jsxref("SharedArrayBuffer")}}.
- `index`
- : The position in the `typedArray` to wake up on.
- `count` {{optional_inline}}
- : The number of sleeping agents to notify. Defaults to {{jsxref("Infinity")}}.
### Return value
- Returns the number of woken up agents.
- Returns `0`, if a non-shared {{jsxref("ArrayBuffer")}} object is used.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `typedArray` is not an {{jsxref("Int32Array")}} or {{jsxref("BigInt64Array")}} that views a {{jsxref("SharedArrayBuffer")}}.
- {{jsxref("RangeError")}}
- : Thrown if `index` is out of bounds in the `typedArray`.
## Examples
### Using `notify`
Given a shared `Int32Array`:
```js
const sab = new SharedArrayBuffer(1024);
const int32 = new Int32Array(sab);
```
A reading thread is sleeping and waiting on location 0 which is expected to be 0. As
long as that is true, it will not go on. However, once the writing thread has stored a
new value, it will be notified by the writing thread and return the new value (123).
```js
Atomics.wait(int32, 0, 0);
console.log(int32[0]); // 123
```
A writing thread stores a new value and notifies the waiting thread once it has
written:
```js
console.log(int32[0]); // 0;
Atomics.store(int32, 0, 123);
Atomics.notify(int32, 0, 1);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Atomics")}}
- {{jsxref("Atomics.wait()")}}
- {{jsxref("Atomics.waitAsync()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics | data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics/load/index.md | ---
title: Atomics.load()
slug: Web/JavaScript/Reference/Global_Objects/Atomics/load
page-type: javascript-static-method
browser-compat: javascript.builtins.Atomics.load
---
{{JSRef}}
The **`Atomics.load()`** static
method returns a value at a given position in the array.
{{EmbedInteractiveExample("pages/js/atomics-load.html")}}
## Syntax
```js-nolint
Atomics.load(typedArray, index)
```
### Parameters
- `typedArray`
- : An integer typed array. One of {{jsxref("Int8Array")}}, {{jsxref("Uint8Array")}},
{{jsxref("Int16Array")}}, {{jsxref("Uint16Array")}}, {{jsxref("Int32Array")}},
{{jsxref("Uint32Array")}}, {{jsxref("BigInt64Array")}}, or
{{jsxref("BigUint64Array")}}.
- `index`
- : The position in the `typedArray` to load from.
### Return value
The value at the given position (`typedArray[index]`).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `typedArray` is not one of the allowed integer types.
- {{jsxref("RangeError")}}
- : Thrown if `index` is out of bounds in the `typedArray`.
## Examples
### Using `load`
```js
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
Atomics.add(ta, 0, 12);
Atomics.load(ta, 0); // 12
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Atomics")}}
- {{jsxref("Atomics.store()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics | data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics/sub/index.md | ---
title: Atomics.sub()
slug: Web/JavaScript/Reference/Global_Objects/Atomics/sub
page-type: javascript-static-method
browser-compat: javascript.builtins.Atomics.sub
---
{{JSRef}}
The **`Atomics.sub()`** static method subtracts a given value
at a given position in the array and returns the old value at that position. This atomic
operation guarantees that no other write happens until the modified value is written
back.
{{EmbedInteractiveExample("pages/js/atomics-sub.html")}}
## Syntax
```js-nolint
Atomics.sub(typedArray, index, value)
```
### Parameters
- `typedArray`
- : An integer typed array. One of {{jsxref("Int8Array")}}, {{jsxref("Uint8Array")}},
{{jsxref("Int16Array")}}, {{jsxref("Uint16Array")}}, {{jsxref("Int32Array")}},
{{jsxref("Uint32Array")}}, {{jsxref("BigInt64Array")}}, or
{{jsxref("BigUint64Array")}}.
- `index`
- : The position in the `typedArray` to subtract a
`value` from.
- `value`
- : The number to subtract.
### Return value
The old value at the given position
(`typedArray[index]`).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `typedArray` is not one of the allowed integer types.
- {{jsxref("RangeError")}}
- : Thrown if `index` is out of bounds in the `typedArray`.
## Examples
### Using sub
```js
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
ta[0] = 48;
Atomics.sub(ta, 0, 12); // returns 48, the old value
Atomics.load(ta, 0); // 36
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Atomics")}}
- {{jsxref("Atomics.add()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics | data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics/compareexchange/index.md | ---
title: Atomics.compareExchange()
slug: Web/JavaScript/Reference/Global_Objects/Atomics/compareExchange
page-type: javascript-static-method
browser-compat: javascript.builtins.Atomics.compareExchange
---
{{JSRef}}
The **`Atomics.compareExchange()`** static method exchanges a given replacement value at a given position in the array, if a given expected value equals the old value. It returns the old value at that position whether it was equal to the expected value or not. This atomic operation guarantees that no other write happens until the modified value is written back.
{{EmbedInteractiveExample("pages/js/atomics-compareexchange.html")}}
## Syntax
```js-nolint
Atomics.compareExchange(typedArray, index, expectedValue, replacementValue)
```
### Parameters
- `typedArray`
- : An integer typed array. One of {{jsxref("Int8Array")}}, {{jsxref("Uint8Array")}}, {{jsxref("Int16Array")}}, {{jsxref("Uint16Array")}}, {{jsxref("Int32Array")}}, {{jsxref("Uint32Array")}}, {{jsxref("BigInt64Array")}}, or {{jsxref("BigUint64Array")}}.
- `index`
- : The position in the `typedArray` to exchange a `replacementValue`.
- `expectedValue`
- : The value to check for equality.
- `replacementValue`
- : The number to exchange.
### Return value
The old value at the given position (`typedArray[index]`).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `typedArray` is not one of the allowed integer types.
- {{jsxref("RangeError")}}
- : Thrown if `index` is out of bounds in the `typedArray`.
## Examples
### Using compareExchange()
```js
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
ta[0] = 7;
Atomics.compareExchange(ta, 0, 7, 12); // returns 7, the old value
Atomics.load(ta, 0); // 12
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Atomics")}}
- {{jsxref("Atomics.exchange()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics | data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics/islockfree/index.md | ---
title: Atomics.isLockFree()
slug: Web/JavaScript/Reference/Global_Objects/Atomics/isLockFree
page-type: javascript-static-method
browser-compat: javascript.builtins.Atomics.isLockFree
---
{{JSRef}}
The **`Atomics.isLockFree()`** static
method is used to determine whether the `Atomics` methods use locks
or atomic hardware operations when applied to typed arrays with the given element
byte size.
It returns `false` if the given size is not one of the [BYTES_PER_ELEMENT](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT)
property of integer TypedArray types.
{{EmbedInteractiveExample("pages/js/atomics-islockfree.html")}}
## Syntax
```js-nolint
Atomics.isLockFree(size)
```
### Parameters
- `size`
- : The size in bytes to check.
### Return value
A `true` or `false` value indicating whether the operation is lock free.
## Examples
### Using isLockFree
```js
Atomics.isLockFree(1); // true
Atomics.isLockFree(2); // true
Atomics.isLockFree(3); // false
Atomics.isLockFree(4); // true
Atomics.isLockFree(5); // false
Atomics.isLockFree(6); // false
Atomics.isLockFree(7); // false
Atomics.isLockFree(8); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Atomics")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/int16array/index.md | ---
title: Int16Array
slug: Web/JavaScript/Reference/Global_Objects/Int16Array
page-type: javascript-class
browser-compat: javascript.builtins.Int16Array
---
{{JSRef}}
The **`Int16Array`** typed array represents an array of 16-bit signed integers in the platform byte order. If control over byte order is needed, use {{jsxref("DataView")}} instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
`Int16Array` is a subclass of the hidden {{jsxref("TypedArray")}} class.
## Constructor
- {{jsxref("Int16Array/Int16Array", "Int16Array()")}}
- : Creates a new `Int16Array` object.
## Static properties
_Also inherits static properties from its parent {{jsxref("TypedArray")}}_.
- {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Int16Array.BYTES_PER_ELEMENT")}}
- : Returns a number value of the element size. `2` in the case of `Int16Array`.
## Static methods
_Inherits static methods from its parent {{jsxref("TypedArray")}}_.
## Instance properties
_Also inherits instance properties from its parent {{jsxref("TypedArray")}}_.
These properties are defined on `Int16Array.prototype` and shared by all `Int16Array` instances.
- {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Int16Array.prototype.BYTES_PER_ELEMENT")}}
- : Returns a number value of the element size. `2` in the case of a `Int16Array`.
- {{jsxref("Object/constructor", "Int16Array.prototype.constructor")}}
- : The constructor function that created the instance object. For `Int16Array` instances, the initial value is the {{jsxref("Int16Array/Int16Array", "Int16Array")}} constructor.
## Instance methods
_Inherits instance methods from its parent {{jsxref("TypedArray")}}_.
## Examples
### Different ways to create an Int16Array
```js
// From a length
const int16 = new Int16Array(2);
int16[0] = 42;
console.log(int16[0]); // 42
console.log(int16.length); // 2
console.log(int16.BYTES_PER_ELEMENT); // 2
// From an array
const x = new Int16Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Int16Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(16);
const z = new Int16Array(buffer, 2, 4);
console.log(z.byteOffset); // 2
// From an iterable
const iterable = (function* () {
yield* [1, 2, 3];
})();
const int16FromIterable = new Int16Array(iterable);
console.log(int16FromIterable);
// Int16Array [1, 2, 3]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Int16Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("TypedArray")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("DataView")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/int16array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/int16array/int16array/index.md | ---
title: Int16Array() constructor
slug: Web/JavaScript/Reference/Global_Objects/Int16Array/Int16Array
page-type: javascript-constructor
browser-compat: javascript.builtins.Int16Array.Int16Array
---
{{JSRef}}
The **`Int16Array()`** constructor creates {{jsxref("Int16Array")}} objects. The contents are initialized to `0`.
## Syntax
```js-nolint
new Int16Array()
new Int16Array(length)
new Int16Array(typedArray)
new Int16Array(object)
new Int16Array(buffer)
new Int16Array(buffer, byteOffset)
new Int16Array(buffer, byteOffset, length)
```
> **Note:** `Int16Array()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters).
### Exceptions
See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions).
## Examples
### Different ways to create an Int16Array
```js
// From a length
const int16 = new Int16Array(2);
int16[0] = 42;
console.log(int16[0]); // 42
console.log(int16.length); // 2
console.log(int16.BYTES_PER_ELEMENT); // 2
// From an array
const x = new Int16Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Int16Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(16);
const z = new Int16Array(buffer, 2, 4);
console.log(z.byteOffset); // 2
// From an iterable
const iterable = (function* () {
yield* [1, 2, 3];
})();
const int16FromIterable = new Int16Array(iterable);
console.log(int16FromIterable);
// Int16Array [1, 2, 3]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Int16Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("TypedArray")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("DataView")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/syntaxerror/index.md | ---
title: SyntaxError
slug: Web/JavaScript/Reference/Global_Objects/SyntaxError
page-type: javascript-class
browser-compat: javascript.builtins.SyntaxError
---
{{JSRef}}
The **`SyntaxError`** object represents an error when trying to interpret syntactically invalid code. It is thrown when the JavaScript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code.
`SyntaxError` is a {{Glossary("serializable object")}}, so it can be cloned with {{domxref("structuredClone()")}} or copied between [Workers](/en-US/docs/Web/API/Worker) using {{domxref("Worker/postMessage()", "postMessage()")}}.
`SyntaxError` is a subclass of {{jsxref("Error")}}.
## Constructor
- {{jsxref("SyntaxError/SyntaxError", "SyntaxError()")}}
- : Creates a new `SyntaxError` object.
## Instance properties
_Also inherits instance properties from its parent {{jsxref("Error")}}_.
These properties are defined on `SyntaxError.prototype` and shared by all `SyntaxError` instances.
- {{jsxref("Object/constructor", "SyntaxError.prototype.constructor")}}
- : The constructor function that created the instance object. For `SyntaxError` instances, the initial value is the {{jsxref("SyntaxError/SyntaxError", "SyntaxError")}} constructor.
- {{jsxref("Error/name", "SyntaxError.prototype.name")}}
- : Represents the name for the type of error. For `SyntaxError.prototype.name`, the initial value is `"SyntaxError"`.
## Instance methods
_Inherits instance methods from its parent {{jsxref("Error")}}_.
## Examples
### Catching a SyntaxError
```js
try {
eval("hoo bar");
} catch (e) {
console.log(e instanceof SyntaxError); // true
console.log(e.message);
console.log(e.name); // "SyntaxError"
console.log(e.stack); // Stack of the error
}
```
### Creating a SyntaxError
```js
try {
throw new SyntaxError("Hello");
} catch (e) {
console.log(e instanceof SyntaxError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "SyntaxError"
console.log(e.stack); // Stack of the error
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Error")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/syntaxerror | data/mdn-content/files/en-us/web/javascript/reference/global_objects/syntaxerror/syntaxerror/index.md | ---
title: SyntaxError() constructor
slug: Web/JavaScript/Reference/Global_Objects/SyntaxError/SyntaxError
page-type: javascript-constructor
browser-compat: javascript.builtins.SyntaxError.SyntaxError
---
{{JSRef}}
The **`SyntaxError()`** constructor creates {{jsxref("SyntaxError")}} objects.
## Syntax
```js-nolint
new SyntaxError()
new SyntaxError(message)
new SyntaxError(message, options)
new SyntaxError(message, fileName)
new SyntaxError(message, fileName, lineNumber)
SyntaxError()
SyntaxError(message)
SyntaxError(message, options)
SyntaxError(message, fileName)
SyntaxError(message, fileName, lineNumber)
```
> **Note:** `SyntaxError()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `SyntaxError` instance.
### Parameters
- `message` {{optional_inline}}
- : Human-readable description of the error
- `options` {{optional_inline}}
- : An object that has the following properties:
- `cause` {{optional_inline}}
- : 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_inline}} {{non-standard_inline}}
- : The name of the file containing the code that caused the exception
- `lineNumber` {{optional_inline}} {{non-standard_inline}}
- : The line number of the code that caused the exception
## Examples
### Catching a SyntaxError
```js
try {
eval("hoo bar");
} catch (e) {
console.log(e instanceof SyntaxError); // true
console.log(e.message);
console.log(e.name); // "SyntaxError"
console.log(e.stack); // Stack of the error
}
```
### Creating a SyntaxError
```js
try {
throw new SyntaxError("Hello");
} catch (e) {
console.log(e instanceof SyntaxError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "SyntaxError"
console.log(e.stack); // Stack of the error
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Error")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect/index.md | ---
title: Reflect
slug: Web/JavaScript/Reference/Global_Objects/Reflect
page-type: javascript-namespace
browser-compat: javascript.builtins.Reflect
---
{{JSRef}}
The **`Reflect`** namespace object contains static methods for invoking interceptable JavaScript object internal methods. The methods are the same as those of [proxy handlers](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy).
## Description
Unlike most global objects, `Reflect` is not a constructor. You cannot use it with the [`new` operator](/en-US/docs/Web/JavaScript/Reference/Operators/new) or invoke the `Reflect` object as a function. All properties and methods of `Reflect` are static (just like the {{jsxref("Math")}} object).
The `Reflect` object provides a collection of static functions which have the same names as the [proxy handler methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy).
The major use case of `Reflect` is to provide default forwarding behavior in `Proxy` handler traps. A [trap](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#terminology) is used to intercept an operation on an object — it provides a custom implementation for an [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). The `Reflect` API is used to invoke the corresponding internal method. For example, the code below creates a proxy `p` with a [`deleteProperty`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/deleteProperty) trap that intercepts the `[[Delete]]` internal method. `Reflect.deleteProperty()` is used to invoke the default `[[Delete]]` behavior on `targetObject` directly. You can replace it with [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/delete), but using `Reflect` saves you from having to remember the syntax that each internal method corresponds to.
```js
const p = new Proxy(
{},
{
deleteProperty(targetObject, property) {
// Custom functionality: log the deletion
console.log("Deleting property:", property);
// Execute the default introspection behavior
return Reflect.deleteProperty(targetObject, property);
},
},
);
```
The `Reflect` methods also allow finer control of how the internal method is invoked. For example, {{jsxref("Reflect.construct()")}} is the only way to construct a target function with a specific [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target) value. If you use the [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) operator to invoke a function, the `new.target` value is always the function itself. This has important effects with [subclassing](/en-US/docs/Web/JavaScript/Reference/Operators/new.target#new.target_using_reflect.construct). For another example, {{jsxref("Reflect.get()")}} allows you to run a [getter](/en-US/docs/Web/JavaScript/Reference/Functions/get) with a custom `this` value, while [property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) always use the current object as the `this` value.
Nearly every `Reflect` method's behavior can be done with some other syntax or method. Some of these methods have corresponding static methods of the same name on {{jsxref("Object")}}, although they do have some subtle differences. For the exact differences, see the description for each `Reflect` method.
## Static properties
- `Reflect[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Reflect"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Static methods
- {{jsxref("Reflect.apply()")}}
- : Calls a `target` function with arguments as specified by the `argumentsList` parameter. See also {{jsxref("Function.prototype.apply()")}}.
- {{jsxref("Reflect.construct()")}}
- : The [`new` operator](/en-US/docs/Web/JavaScript/Reference/Operators/new) as a function. Equivalent to calling `new target(...argumentsList)`. Also provides the option to specify a different prototype.
- {{jsxref("Reflect.defineProperty()")}}
- : Similar to {{jsxref("Object.defineProperty()")}}. Returns a boolean that is `true` if the property was successfully defined.
- {{jsxref("Reflect.deleteProperty()")}}
- : The [`delete` operator](/en-US/docs/Web/JavaScript/Reference/Operators/delete) as a function. Equivalent to calling `delete target[propertyKey]`.
- {{jsxref("Reflect.get()")}}
- : Returns the value of the property. Works like getting a property from an object (`target[propertyKey]`) as a function.
- {{jsxref("Reflect.getOwnPropertyDescriptor()")}}
- : Similar to {{jsxref("Object.getOwnPropertyDescriptor()")}}. Returns a property descriptor of the given property if it exists on the object, {{jsxref("undefined")}} otherwise.
- {{jsxref("Reflect.getPrototypeOf()")}}
- : Same as {{jsxref("Object.getPrototypeOf()")}}.
- {{jsxref("Reflect.has()")}}
- : Returns a boolean indicating whether the target has the property. Either as own or inherited. Works like the [`in` operator](/en-US/docs/Web/JavaScript/Reference/Operators/in) as a function.
- {{jsxref("Reflect.isExtensible()")}}
- : Same as {{jsxref("Object.isExtensible()")}}. Returns a boolean that is `true` if the target is extensible.
- {{jsxref("Reflect.ownKeys()")}}
- : Returns an array of the target object's own (not inherited) property keys.
- {{jsxref("Reflect.preventExtensions()")}}
- : Similar to {{jsxref("Object.preventExtensions()")}}. Returns a boolean that is `true` if the update was successful.
- {{jsxref("Reflect.set()")}}
- : A function that assigns values to properties. Returns a boolean that is `true` if the update was successful.
- {{jsxref("Reflect.setPrototypeOf()")}}
- : A function that sets the prototype of an object. Returns a boolean that is `true` if the update was successful.
## Examples
### Detecting whether an object contains certain properties
```js
const duck = {
name: "Maurice",
color: "white",
greeting() {
console.log(`Quaaaack! My name is ${this.name}`);
},
};
Reflect.has(duck, "color");
// true
Reflect.has(duck, "haircut");
// false
```
### Returning the object's own keys
```js
Reflect.ownKeys(duck);
// [ "name", "color", "greeting" ]
```
### Adding a new property to the object
```js
Reflect.set(duck, "eyes", "black");
// returns "true" if successful
// "duck" now contains the property "eyes: 'black'"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Proxy")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect | data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect/construct/index.md | ---
title: Reflect.construct()
slug: Web/JavaScript/Reference/Global_Objects/Reflect/construct
page-type: javascript-static-method
browser-compat: javascript.builtins.Reflect.construct
---
{{JSRef}}
The **`Reflect.construct()`** static method is like the {{jsxref("Operators/new", "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`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target) value.
{{EmbedInteractiveExample("pages/js/reflect-construct.html", "taller")}}
## Syntax
```js-nolint
Reflect.construct(target, argumentsList)
Reflect.construct(target, argumentsList, newTarget)
```
### Parameters
- `target`
- : The target function to call.
- `argumentsList`
- : An [array-like object](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects) specifying the arguments with which `target` should be called.
- `newTarget` {{optional_inline}}
- : The value of [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/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
- {{jsxref("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`](/en-US/docs/Web/JavaScript/Reference/Operators/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](/en-US/docs/Web/JavaScript/Reference/Operators/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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods) 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 {{jsxref("Object.create()")}}.
```js
function OneClass() {
this.name = "one";
}
function OtherClass() {
this.name = "other";
}
const args = [];
const obj1 = Reflect.construct(OneClass, args, OtherClass);
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
```
However, while the end result is the same, there is one important difference in the process. When using `Object.create()` and {{jsxref("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`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Reflect.construct` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
- {{jsxref("Reflect")}}
- {{jsxref("Operators/new", "new")}}
- [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target)
- [`handler.construct()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/construct)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect | data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect/get/index.md | ---
title: Reflect.get()
slug: Web/JavaScript/Reference/Global_Objects/Reflect/get
page-type: javascript-static-method
browser-compat: javascript.builtins.Reflect.get
---
{{JSRef}}
The **`Reflect.get()`** static method is like the [property accessor](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) syntax, but as a function.
{{EmbedInteractiveExample("pages/js/reflect-get.html")}}
## Syntax
```js-nolint
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_inline}}
- : The value of `this` provided for the call to `target` if a getter is encountered.
### Return value
The value of the property.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `target` is not an object.
## Description
`Reflect.get()` provides the reflective semantic of a [property access](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors). 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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods) 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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Reflect.get` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
- {{jsxref("Reflect")}}
- [Property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors)
- [`handler.get()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/get)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect | data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect/setprototypeof/index.md | ---
title: Reflect.setPrototypeOf()
slug: Web/JavaScript/Reference/Global_Objects/Reflect/setPrototypeOf
page-type: javascript-static-method
browser-compat: javascript.builtins.Reflect.setPrototypeOf
---
{{JSRef}}
The **`Reflect.setPrototypeOf()`** static method is like {{jsxref("Object.setPrototypeOf()")}} but returns a {{jsxref("Boolean")}}. It sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object.
{{EmbedInteractiveExample("pages/js/reflect-setprototypeof.html")}}
## Syntax
```js-nolint
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`](/en-US/docs/Web/JavaScript/Reference/Operators/null)).
### Return value
A {{jsxref("Boolean")}} indicating whether or not the prototype was successfully set.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `target` is not an object or if `prototype` is neither an object nor [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/setPrototypeOf)). {{jsxref("Object.setPrototypeOf()")}} provides nearly the same semantic, but it throws a {{jsxref("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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods) 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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Reflect.setPrototypeOf` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
- {{jsxref("Reflect")}}
- {{jsxref("Object.setPrototypeOf()")}}
- [`handler.setPrototypeOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/setPrototypeOf)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect | data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect/has/index.md | ---
title: Reflect.has()
slug: Web/JavaScript/Reference/Global_Objects/Reflect/has
page-type: javascript-static-method
browser-compat: javascript.builtins.Reflect.has
---
{{JSRef}}
The **`Reflect.has()`** static method is like the [`in`](/en-US/docs/Web/JavaScript/Reference/Operators/in) operator, but
as a function.
{{EmbedInteractiveExample("pages/js/reflect-has.html")}}
## Syntax
```js-nolint
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 {{jsxref("Boolean")}} indicating whether or not the `target` has the property.
### Exceptions
- {{jsxref("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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods) 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`](/en-US/docs/Web/JavaScript/Reference/Operators/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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Reflect.has` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
- {{jsxref("Reflect")}}
- [`in`](/en-US/docs/Web/JavaScript/Reference/Operators/in)
- [`handler.has()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/has)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect | data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect/set/index.md | ---
title: Reflect.set()
slug: Web/JavaScript/Reference/Global_Objects/Reflect/set
page-type: javascript-static-method
browser-compat: javascript.builtins.Reflect.set
---
{{JSRef}}
The **`Reflect.set()`** static method is like the [property accessor](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) and [assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Assignment) syntax, but as a function.
{{EmbedInteractiveExample("pages/js/reflect-set.html")}}
## Syntax
```js-nolint
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_inline}}
- : 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 {{jsxref("Boolean")}} indicating whether or not setting the property was successful.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `target` is not an object.
## Description
`Reflect.set()` provides the reflective semantic of a [property access](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors). 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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods) 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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Reflect.set` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
- {{jsxref("Reflect")}}
- [Property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors)
- [`handler.set()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/set)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect | data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect/getownpropertydescriptor/index.md | ---
title: Reflect.getOwnPropertyDescriptor()
slug: Web/JavaScript/Reference/Global_Objects/Reflect/getOwnPropertyDescriptor
page-type: javascript-static-method
browser-compat: javascript.builtins.Reflect.getOwnPropertyDescriptor
---
{{JSRef}}
The **`Reflect.getOwnPropertyDescriptor()`** static method is like {{jsxref("Object.getOwnPropertyDescriptor()")}}. It returns a property descriptor of the given property if it exists on the object, {{jsxref("undefined")}} otherwise.
{{EmbedInteractiveExample("pages/js/reflect-getownpropertydescriptor.html")}}
## Syntax
```js-nolint
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, {{jsxref("undefined")}}.
### Exceptions
- {{jsxref("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 {{jsxref("Object.getOwnPropertyDescriptor()")}} is how non-object targets are handled. `Reflect.getOwnPropertyDescriptor()` throws a {{jsxref("TypeError")}} if the target is not an object, while `Object.getOwnPropertyDescriptor()` coerces it to an object.
`Reflect.getOwnPropertyDescriptor()` invokes the `[[GetOwnProperty]]` [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods) 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 {{jsxref("TypeError")}}. With {{jsxref("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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Reflect.getOwnPropertyDescriptor` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
- {{jsxref("Reflect")}}
- {{jsxref("Object.getOwnPropertyDescriptor()")}}
- [`handler.getOwnPropertyDescriptor()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/getOwnPropertyDescriptor)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect | data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect/getprototypeof/index.md | ---
title: Reflect.getPrototypeOf()
slug: Web/JavaScript/Reference/Global_Objects/Reflect/getPrototypeOf
page-type: javascript-static-method
browser-compat: javascript.builtins.Reflect.getPrototypeOf
---
{{JSRef}}
The **`Reflect.getPrototypeOf()`** static method is like {{jsxref("Object.getPrototypeOf()")}}. It returns the prototype of the specified object.
{{EmbedInteractiveExample("pages/js/reflect-getprototypeof.html")}}
## Syntax
```js-nolint
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
- {{jsxref("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 {{jsxref("Object.getPrototypeOf()")}} is how non-object targets are handled. `Reflect.getPrototypeOf()` throws a {{jsxref("TypeError")}} if the target is not an object, while `Object.getPrototypeOf()` coerces it to an object.
`Reflect.getPrototypeOf()` invokes the `[[GetPrototypeOf]]` [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods) 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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Reflect.getPrototypeOf` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
- {{jsxref("Reflect")}}
- {{jsxref("Object.getPrototypeOf()")}}
- [`handler.getPrototypeOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/getPrototypeOf)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect | data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect/ownkeys/index.md | ---
title: Reflect.ownKeys()
slug: Web/JavaScript/Reference/Global_Objects/Reflect/ownKeys
page-type: javascript-static-method
browser-compat: javascript.builtins.Reflect.ownKeys
---
{{JSRef}}
The **`Reflect.ownKeys()`** static method returns an array of the `target` object's own property keys.
{{EmbedInteractiveExample("pages/js/reflect-ownkeys.html")}}
## Syntax
```js-nolint
Reflect.ownKeys(target)
```
### Parameters
- `target`
- : The target object from which to get the own keys.
### Return value
An {{jsxref("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
- {{jsxref("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, {{jsxref("Object.getOwnPropertyNames()")}} takes the return value of `Reflect.ownKeys()` and filters to only string values, while {{jsxref("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`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/ownKeys) handler), the order of the keys may be different.
`Reflect.ownKeys()` invokes the `[[OwnPropertyKeys]]` [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods) 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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Reflect.ownKeys` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
- {{jsxref("Reflect")}}
- {{jsxref("Object.getOwnPropertyNames()")}}
- {{jsxref("Object.getOwnPropertySymbols()")}}
- [`handler.ownKeys()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/ownKeys)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect | data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect/deleteproperty/index.md | ---
title: Reflect.deleteProperty()
slug: Web/JavaScript/Reference/Global_Objects/Reflect/deleteProperty
page-type: javascript-static-method
browser-compat: javascript.builtins.Reflect.deleteProperty
---
{{JSRef}}
The **`Reflect.deleteProperty()`** static method is like the {{jsxref("Operators/delete", "delete")}} operator, but as a function. It deletes a property from an object.
{{EmbedInteractiveExample("pages/js/reflect-deleteproperty.html", "taller")}}
## Syntax
```js-nolint
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
- {{jsxref("TypeError")}}
- : Thrown if `target` is not an object.
## Description
`Reflect.deleteProperty()` provides the reflective semantic of the [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/deleteProperty)). `Reflect.deleteProperty()` directly returns the status, while `delete` would throw a {{jsxref("TypeError")}} in [strict mode](/en-US/docs/Web/JavaScript/Reference/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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods) 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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Reflect.deleteProperty` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
- {{jsxref("Reflect")}}
- [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/delete)
- [`handler.deleteProperty()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/deleteProperty)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect | data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect/isextensible/index.md | ---
title: Reflect.isExtensible()
slug: Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible
page-type: javascript-static-method
browser-compat: javascript.builtins.Reflect.isExtensible
---
{{JSRef}}
The **`Reflect.isExtensible()`** static method is like {{jsxref("Object.isExtensible()")}}. It determines if an object is extensible (whether it can have new properties added to it).
{{EmbedInteractiveExample("pages/js/reflect-isextensible.html", "taller")}}
## Syntax
```js-nolint
Reflect.isExtensible(target)
```
### Parameters
- `target`
- : The target object which to check if it is extensible.
### Return value
A {{jsxref("Boolean")}} indicating whether or not the target is extensible.
### Exceptions
- {{jsxref("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 {{jsxref("Object.isExtensible()")}} is how non-object targets are handled. `Reflect.isExtensible()` throws a {{jsxref("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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods) of `target`.
## Examples
### Using Reflect.isExtensible()
See also {{jsxref("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 {{jsxref("TypeError")}}. With {{jsxref("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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Reflect.isExtensible` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
- {{jsxref("Reflect")}}
- {{jsxref("Object.isExtensible()")}}
- [`handler.isExtensible()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/isExtensible)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect | data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect/apply/index.md | ---
title: Reflect.apply()
slug: Web/JavaScript/Reference/Global_Objects/Reflect/apply
page-type: javascript-static-method
browser-compat: javascript.builtins.Reflect.apply
---
{{JSRef}}
The **`Reflect.apply()`** static method calls a target function with arguments as specified.
{{EmbedInteractiveExample("pages/js/reflect-apply.html", "taller")}}
## Syntax
```js-nolint
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](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects) 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
- {{jsxref("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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods) 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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Reflect.apply` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
- {{jsxref("Reflect")}}
- {{jsxref("Function.prototype.apply()")}}
- [`handler.apply()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect | data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect/preventextensions/index.md | ---
title: Reflect.preventExtensions()
slug: Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions
page-type: javascript-static-method
browser-compat: javascript.builtins.Reflect.preventExtensions
---
{{JSRef}}
The **`Reflect.preventExtensions()`** static method is like {{jsxref("Object.preventExtensions()")}}. It prevents new properties from ever being added to an object (i.e., prevents future extensions to the object).
{{EmbedInteractiveExample("pages/js/reflect-preventextensions.html")}}
## Syntax
```js-nolint
Reflect.preventExtensions(target)
```
### Parameters
- `target`
- : The target object on which to prevent extensions.
### Return value
A {{jsxref("Boolean")}} indicating whether or not the target was successfully set to prevent extensions.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `target` is not an object.
## Description
`Reflect.preventExtensions()` provides the reflective semantic of preventing extensions of an object. The differences with {{jsxref("Object.preventExtensions()")}} are:
- `Reflect.preventExtensions()` throws a {{jsxref("TypeError")}} if the target is not an object, while `Object.preventExtensions()` always returns non-object targets as-is.
- `Reflect.preventExtensions()` returns a {{jsxref("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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods) of `target`.
## Examples
### Using Reflect.preventExtensions()
See also {{jsxref("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 {{jsxref("TypeError")}}. With {{jsxref("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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Reflect.preventExtensions` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
- {{jsxref("Reflect")}}
- {{jsxref("Object.preventExtensions()")}}
- [`handler.preventExtensions()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/preventExtensions)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect | data/mdn-content/files/en-us/web/javascript/reference/global_objects/reflect/defineproperty/index.md | ---
title: Reflect.defineProperty()
slug: Web/JavaScript/Reference/Global_Objects/Reflect/defineProperty
page-type: javascript-static-method
browser-compat: javascript.builtins.Reflect.defineProperty
---
{{JSRef}}
The **`Reflect.defineProperty()`** static method is like {{jsxref("Object.defineProperty()")}} but returns a {{jsxref("Boolean")}}.
{{EmbedInteractiveExample("pages/js/reflect-defineproperty.html")}}
## Syntax
```js-nolint
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
- {{jsxref("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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/defineProperty)). {{jsxref("Object.defineProperty()")}} provides nearly the same semantic, but it throws a {{jsxref("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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/set) them is that [setters](/en-US/docs/Web/JavaScript/Reference/Functions/set) aren't invoked. For example, [class fields](/en-US/docs/Web/JavaScript/Reference/Classes/Public_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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods) 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 {{jsxref("Object.defineProperty()")}}, which returns an object if successful, or throws a {{jsxref("TypeError")}} otherwise, you would use a [`try...catch`](/en-US/docs/Web/JavaScript/Reference/Statements/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`](/en-US/docs/Web/JavaScript/Reference/Statements/if...else) block here:
```js
if (Reflect.defineProperty(target, property, attributes)) {
// success
} else {
// failure
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Reflect.defineProperty` in `core-js`](https://github.com/zloirock/core-js#ecmascript-reflect)
- {{jsxref("Reflect")}}
- {{jsxref("Object.defineProperty()")}}
- [`handler.defineProperty()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/defineProperty)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/uint32array/index.md | ---
title: Uint32Array
slug: Web/JavaScript/Reference/Global_Objects/Uint32Array
page-type: javascript-class
browser-compat: javascript.builtins.Uint32Array
---
{{JSRef}}
The **`Uint32Array`** typed array represents an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use {{jsxref("DataView")}} instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
`Uint32Array` is a subclass of the hidden {{jsxref("TypedArray")}} class.
## Constructor
- {{jsxref("Uint32Array/Uint32Array", "Uint32Array()")}}
- : Creates a new `Uint32Array` object.
## Static properties
_Also inherits static properties from its parent {{jsxref("TypedArray")}}_.
- {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Uint32Array.BYTES_PER_ELEMENT")}}
- : Returns a number value of the element size. `4` in the case of `Uint32Array`.
## Static methods
_Inherits static methods from its parent {{jsxref("TypedArray")}}_.
## Instance properties
_Also inherits instance properties from its parent {{jsxref("TypedArray")}}_.
These properties are defined on `Uint32Array.prototype` and shared by all `Uint32Array` instances.
- {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Uint32Array.prototype.BYTES_PER_ELEMENT")}}
- : Returns a number value of the element size. `4` in the case of a `Uint32Array`.
- {{jsxref("Object/constructor", "Uint32Array.prototype.constructor")}}
- : The constructor function that created the instance object. For `Uint32Array` instances, the initial value is the {{jsxref("Uint32Array/Uint32Array", "Uint32Array")}} constructor.
## Instance methods
_Inherits instance methods from its parent {{jsxref("TypedArray")}}_.
## Examples
### Different ways to create a Uint32Array
```js
// From a length
const uint32 = new Uint32Array(2);
uint32[0] = 42;
console.log(uint32[0]); // 42
console.log(uint32.length); // 2
console.log(uint32.BYTES_PER_ELEMENT); // 4
// From an array
const x = new Uint32Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Uint32Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(32);
const z = new Uint32Array(buffer, 4, 4);
console.log(z.byteOffset); // 4
// From an iterable
const iterable = (function* () {
yield* [1, 2, 3];
})();
const uint32FromIterable = new Uint32Array(iterable);
console.log(uint32FromIterable);
// Uint32Array [1, 2, 3]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Uint32Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("TypedArray")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("DataView")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/uint32array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/uint32array/uint32array/index.md | ---
title: Uint32Array() constructor
slug: Web/JavaScript/Reference/Global_Objects/Uint32Array/Uint32Array
page-type: javascript-constructor
browser-compat: javascript.builtins.Uint32Array.Uint32Array
---
{{JSRef}}
The **`Uint32Array()`** constructor creates {{jsxref("Uint32Array")}} objects. The contents are initialized to `0`.
## Syntax
```js-nolint
new Uint32Array()
new Uint32Array(length)
new Uint32Array(typedArray)
new Uint32Array(object)
new Uint32Array(buffer)
new Uint32Array(buffer, byteOffset)
new Uint32Array(buffer, byteOffset, length)
```
> **Note:** `Uint32Array()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters).
### Exceptions
See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions).
## Examples
### Different ways to create a Uint32Array
```js
// From a length
const uint32 = new Uint32Array(2);
uint32[0] = 42;
console.log(uint32[0]); // 42
console.log(uint32.length); // 2
console.log(uint32.BYTES_PER_ELEMENT); // 4
// From an array
const x = new Uint32Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Uint32Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(32);
const z = new Uint32Array(buffer, 4, 4);
console.log(z.byteOffset); // 4
// From an iterable
const iterable = (function* () {
yield* [1, 2, 3];
})();
const uint32FromIterable = new Uint32Array(iterable);
console.log(uint32FromIterable);
// Uint32Array [1, 2, 3]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Uint32Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("TypedArray")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("DataView")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/parsefloat/index.md | ---
title: parseFloat()
slug: Web/JavaScript/Reference/Global_Objects/parseFloat
page-type: javascript-function
browser-compat: javascript.builtins.parseFloat
---
{{jsSidebar("Objects")}}
The **`parseFloat()`** function parses a string argument and returns a floating point number.
{{EmbedInteractiveExample("pages/js/globalprops-parsefloat.html")}}
## Syntax
```js-nolint
parseFloat(string)
```
### Parameters
- `string`
- : The value to parse, [coerced to a string](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading {{Glossary("whitespace")}} in this argument is ignored.
### Return value
A floating point number parsed from the given `string`, or {{jsxref("NaN")}} when the first non-whitespace character cannot be converted to a number.
> **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. [`parseInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) and `parseFloat()` only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a {{jsxref("Number")}} 42.
## Description
The `parseFloat` function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or `NaN`. The number syntax it accepts can be summarized as:
- The characters accepted by `parseFloat()` are plus sign (`+`), minus sign (`-` U+002D HYPHEN-MINUS), decimal digits (`0` – `9`), decimal point (`.`), exponent indicator (`e` or `E`), and the `"Infinity"` literal.
- The `+`/`-` signs can only appear strictly at the beginning of the string, or immediately following the `e`/`E` character. The decimal point can only appear once, and only before the `e`/`E` character. The `e`/`E` character can only appear once, and only if there is at least one digit before it.
- Leading spaces in the argument are trimmed and ignored.
- `parseFloat()` can also parse and return {{jsxref("Infinity")}} or `-Infinity` if the string starts with `"Infinity"` or `"-Infinity"` preceded by none or more white spaces.
- `parseFloat()` picks the longest substring starting from the beginning that generates a valid number literal. If it encounters an invalid character, it returns the number represented up to that point, ignoring the invalid character and all characters following it.
- If the argument's first character can't start a legal number literal per the syntax above, `parseFloat` returns {{jsxref("NaN")}}.
Syntax-wise, `parseFloat()` parses a subset of the syntax that the [`Number()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number) function accepts. Namely, `parseFloat()` does not support non-decimal literals with `0x`, `0b`, or `0o` prefixes but supports everything else. However, `parseFloat()` is more lenient than `Number()` because it ignores trailing invalid characters, which would cause `Number()` to return `NaN`.
Similar to number literals and `Number()`, the number returned from `parseFloat()` may not be exactly equal to the number represented by the string, due to floating point range and inaccuracy. For numbers outside the `-1.7976931348623158e+308` – `1.7976931348623158e+308` range (see {{jsxref("Number.MAX_VALUE")}}), `-Infinity` or `Infinity` is returned.
## Examples
### Using parseFloat()
The following examples all return `3.14`:
```js
parseFloat(3.14);
parseFloat("3.14");
parseFloat(" 3.14 ");
parseFloat("314e-2");
parseFloat("0.0314E+2");
parseFloat("3.14some non-digit characters");
parseFloat({
toString() {
return "3.14";
},
});
```
### parseFloat() returning NaN
The following example returns `NaN`:
```js
parseFloat("FF2");
```
Anecdotally, because the string `NaN` itself is invalid syntax as accepted by `parseFloat()`, passing `"NaN"` returns `NaN` as well.
```js
parseFloat("NaN"); // NaN
```
### Returning Infinity
Infinity values are returned when the number is outside the double-precision 64-bit IEEE 754-2019 format range:
```js
parseFloat("1.7976931348623159e+308"); // Infinity
parseFloat("-1.7976931348623159e+308"); // -Infinity
```
Infinity is also returned when the string starts with `"Infinity"` or `"-Infinity"`:
```js
parseFloat("Infinity"); // Infinity
parseFloat("-Infinity"); // -Infinity
```
### Interaction with BigInt values
`parseFloat()` does not handle {{jsxref("BigInt")}} values. It stops at the `n` character, and treats the preceding string as a normal integer, with possible loss of precision. If a BigInt value is passed to `parseFloat()`, it will be converted to a string, and the string will be parsed as a floating-point number, which may result in loss of precision as well.
```js example-bad
parseFloat(900719925474099267n); // 900719925474099300
parseFloat("900719925474099267n"); // 900719925474099300
```
You should pass the string to the [`BigInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt) function instead, without the trailing `n` character.
```js example-good
BigInt("900719925474099267");
// 900719925474099267n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("parseInt()")}}
- {{jsxref("Number.parseFloat()")}}
- {{jsxref("Number.parseInt()")}}
- {{jsxref("Number.prototype.toFixed()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/index.md | ---
title: DataView
slug: Web/JavaScript/Reference/Global_Objects/DataView
page-type: javascript-class
browser-compat: javascript.builtins.DataView
---
{{JSRef}}
The **`DataView`** view provides a low-level interface for reading and writing multiple number types in a binary {{jsxref("ArrayBuffer")}}, without having to care about the platform's [endianness](/en-US/docs/Glossary/Endianness).
## Description
### Endianness
Multi-byte number formats are represented in memory differently depending on machine architecture — see [Endianness](/en-US/docs/Glossary/Endianness) for an explanation. `DataView` accessors provide explicit control of how data is accessed, regardless of the executing computer's endianness.
```js
const littleEndian = (() => {
const buffer = new ArrayBuffer(2);
new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
// Int16Array uses the platform's endianness.
return new Int16Array(buffer)[0] === 256;
})();
console.log(littleEndian); // true or false
```
### 64-bit Integer Values
Some browsers don't have support for {{jsxref("DataView.prototype.setBigInt64()")}} and {{jsxref("DataView.prototype.setBigUint64()")}}. So to enable 64-bit operations in your code that will work across browsers, you could implement your own `getUint64()` function, to obtain values with precision up to {{jsxref("Number.MAX_SAFE_INTEGER")}} — which could suffice for certain cases.
```js
function getUint64(dataview, byteOffset, littleEndian) {
// split 64-bit number into two 32-bit (4-byte) parts
const left = dataview.getUint32(byteOffset, littleEndian);
const right = dataview.getUint32(byteOffset + 4, littleEndian);
// combine the two 32-bit values
const combined = littleEndian
? left + 2 ** 32 * right
: 2 ** 32 * left + right;
if (!Number.isSafeInteger(combined))
console.warn(combined, "exceeds MAX_SAFE_INTEGER. Precision may be lost");
return combined;
}
```
Alternatively, if you need full 64-bit range, you can create a {{jsxref("BigInt")}}. Further, although native BigInts are much faster than user-land library equivalents, BigInts will always be much slower than 32-bit integers in JavaScript due to the nature of their variable size.
```js
const BigInt = window.BigInt,
bigThirtyTwo = BigInt(32),
bigZero = BigInt(0);
function getUint64BigInt(dataview, byteOffset, littleEndian) {
// split 64-bit number into two 32-bit (4-byte) parts
const left = BigInt(dataview.getUint32(byteOffset | 0, !!littleEndian) >>> 0);
const right = BigInt(
dataview.getUint32(((byteOffset | 0) + 4) | 0, !!littleEndian) >>> 0,
);
// combine the two 32-bit values and return
return littleEndian
? (right << bigThirtyTwo) | left
: (left << bigThirtyTwo) | right;
}
```
## Constructor
- {{jsxref("DataView/DataView", "DataView()")}}
- : Creates a new `DataView` object.
## Instance properties
These properties are defined on `DataView.prototype` and shared by all `DataView` instances.
- {{jsxref("DataView.prototype.buffer")}}
- : The {{jsxref("ArrayBuffer")}} referenced by this view. Fixed at construction time and thus **read only.**
- {{jsxref("DataView.prototype.byteLength")}}
- : The length (in bytes) of this view. Fixed at construction time and thus **read only.**
- {{jsxref("DataView.prototype.byteOffset")}}
- : The offset (in bytes) of this view from the start of its {{jsxref("ArrayBuffer")}}. Fixed at construction time and thus **read only.**
- {{jsxref("Object/constructor", "DataView.prototype.constructor")}}
- : The constructor function that created the instance object. For `DataView` instances, the initial value is the {{jsxref("DataView/DataView", "DataView")}} constructor.
- `DataView.prototype[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"DataView"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Instance methods
- {{jsxref("DataView.prototype.getBigInt64()")}}
- : Reads 8 bytes starting at the specified byte offset of this `DataView` and interprets them as a 64-bit signed integer.
- {{jsxref("DataView.prototype.getBigUint64()")}}
- : Reads 8 bytes starting at the specified byte offset of this `DataView` and interprets them as a 64-bit unsigned integer.
- {{jsxref("DataView.prototype.getFloat32()")}}
- : Reads 4 bytes starting at the specified byte offset of this `DataView` and interprets them as a 32-bit floating point number.
- {{jsxref("DataView.prototype.getFloat64()")}}
- : Reads 8 bytes starting at the specified byte offset of this `DataView` and interprets them as a 64-bit floating point number.
- {{jsxref("DataView.prototype.getInt16()")}}
- : Reads 2 bytes starting at the specified byte offset of this `DataView` and interprets them as a 16-bit signed integer.
- {{jsxref("DataView.prototype.getInt32()")}}
- : Reads 4 bytes starting at the specified byte offset of this `DataView` and interprets them as a 32-bit signed integer.
- {{jsxref("DataView.prototype.getInt8()")}}
- : Reads 1 byte at the specified byte offset of this `DataView` and interprets it as an 8-bit signed integer.
- {{jsxref("DataView.prototype.getUint16()")}}
- : Reads 2 bytes starting at the specified byte offset of this `DataView` and interprets them as a 16-bit unsigned integer.
- {{jsxref("DataView.prototype.getUint32()")}}
- : Reads 4 bytes starting at the specified byte offset of this `DataView` and interprets them as a 32-bit unsigned integer.
- {{jsxref("DataView.prototype.getUint8()")}}
- : Reads 1 byte at the specified byte offset of this `DataView` and interprets it as an 8-bit unsigned integer.
- {{jsxref("DataView.prototype.setBigInt64()")}}
- : Takes a BigInt and stores it as a 64-bit signed integer in the 8 bytes starting at the specified byte offset of this `DataView`.
- {{jsxref("DataView.prototype.setBigUint64()")}}
- : Takes a BigInt and stores it as a 64-bit unsigned integer in the 8 bytes starting at the specified byte offset of this `DataView`.
- {{jsxref("DataView.prototype.setFloat32()")}}
- : Takes a number and stores it as a 32-bit float in the 4 bytes starting at the specified byte offset of this `DataView`.
- {{jsxref("DataView.prototype.setFloat64()")}}
- : Takes a number and stores it as a 64-bit float in the 8 bytes starting at the specified byte offset of this `DataView`.
- {{jsxref("DataView.prototype.setInt16()")}}
- : Takes a number and stores it as a 16-bit signed integer in the 2 bytes at the specified byte offset of this `DataView`.
- {{jsxref("DataView.prototype.setInt32()")}}
- : Takes a number and stores it as a 32-bit signed integer in the 4 bytes at the specified byte offset of this `DataView`.
- {{jsxref("DataView.prototype.setInt8()")}}
- : Takes a number and stores it as an 8-bit signed integer in the byte at the specified byte offset of this `DataView`.
- {{jsxref("DataView.prototype.setUint16()")}}
- : Takes a number and stores it as a 16-bit unsigned integer in the 2 bytes at the specified byte offset of this `DataView`.
- {{jsxref("DataView.prototype.setUint32()")}}
- : Takes a number and stores it as a 32-bit unsigned integer in the 4 bytes at the specified byte offset of this `DataView`.
- {{jsxref("DataView.prototype.setUint8()")}}
- : Takes a number and stores it as an 8-bit unsigned integer in the byte at the specified byte offset of this `DataView`.
## Examples
### Using DataView
```js
const buffer = new ArrayBuffer(16);
const view = new DataView(buffer, 0);
view.setInt16(1, 42);
view.getInt16(1); // 42
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `DataView` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
- {{jsxref("ArrayBuffer")}}
- {{jsxref("SharedArrayBuffer")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/setuint32/index.md | ---
title: DataView.prototype.setUint32()
slug: Web/JavaScript/Reference/Global_Objects/DataView/setUint32
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.setUint32
---
{{JSRef}}
The **`setUint32()`** method of {{jsxref("DataView")}} instances takes a number and stores it as a 32-bit unsigned integer in the 4 bytes starting at the specified byte offset of this `DataView`. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.
{{EmbedInteractiveExample("pages/js/dataview-setuint32.html")}}
## Syntax
```js-nolint
setUint32(byteOffset, value)
setUint32(byteOffset, value, littleEndian)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to store the data in.
- `value`
- : The value to set. For how the value is encoded in bytes, see [Value encoding and normalization](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#value_encoding_and_normalization).
- `littleEndian` {{optional_inline}}
- : Indicates whether the data is stored in [little- or big-endian](/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written.
### Return value
{{jsxref("undefined")}}.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would store beyond the end of the view.
## Examples
### Using setUint32()
```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setUint32(0, 3);
dataview.getUint32(1); // 768
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("Uint32Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/setuint8/index.md | ---
title: DataView.prototype.setUint8()
slug: Web/JavaScript/Reference/Global_Objects/DataView/setUint8
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.setUint8
---
{{JSRef}}
The **`setUint8()`** method of {{jsxref("DataView")}} instances takes a number and stores it as an 8-bit unsigned integer in the byte at the specified byte offset of this `DataView`.
{{EmbedInteractiveExample("pages/js/dataview-setuint8.html")}}
## Syntax
```js-nolint
setUint8(byteOffset, value)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to store the data in.
- `value`
- : The value to set. For how the value is encoded in bytes, see [Value encoding and normalization](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#value_encoding_and_normalization).
### Return value
{{jsxref("undefined")}}.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would store beyond the end of the view.
## Examples
### Using setUint8()
```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setUint8(0, 3);
dataview.getUint8(0); // 3
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("Uint8Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/byteoffset/index.md | ---
title: DataView.prototype.byteOffset
slug: Web/JavaScript/Reference/Global_Objects/DataView/byteOffset
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.DataView.byteOffset
---
{{JSRef}}
The **`byteOffset`** accessor property of {{jsxref("DataView")}} instances returns the offset (in bytes) of this view from the start of its {{jsxref("ArrayBuffer")}} or {{jsxref("SharedArrayBuffer")}}.
{{EmbedInteractiveExample("pages/js/dataview-byteoffset.html")}}
## Description
The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed.
## Examples
### Using the byteOffset property
```js
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.byteOffset; // 0 (no offset specified)
const dataview2 = new DataView(buffer, 3);
dataview2.byteOffset; // 3 (as specified when constructing the DataView)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("SharedArrayBuffer")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/buffer/index.md | ---
title: DataView.prototype.buffer
slug: Web/JavaScript/Reference/Global_Objects/DataView/buffer
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.DataView.buffer
---
{{JSRef}}
The **`buffer`** accessor property of {{jsxref("DataView")}} instances returns the {{jsxref("ArrayBuffer")}} or {{jsxref("SharedArrayBuffer")}} referenced by this view at construction time.
{{EmbedInteractiveExample("pages/js/dataview-buffer.html")}}
## Description
The `buffer` 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 `DataView` is constructed and cannot be changed.
## Examples
### Using the buffer property
```js
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.buffer; // ArrayBuffer { byteLength: 8 }
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("SharedArrayBuffer")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/setint8/index.md | ---
title: DataView.prototype.setInt8()
slug: Web/JavaScript/Reference/Global_Objects/DataView/setInt8
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.setInt8
---
{{JSRef}}
The **`setInt8()`** method of {{jsxref("DataView")}} instances takes a number and stores it as an 8-bit signed integer in the byte at the specified byte offset of this `DataView`.
{{EmbedInteractiveExample("pages/js/dataview-setint8.html")}}
## Syntax
```js-nolint
setInt8(byteOffset, value)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to store the data in.
- `value`
- : The value to set. For how the value is encoded in bytes, see [Value encoding and normalization](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#value_encoding_and_normalization).
### Return value
{{jsxref("undefined")}}.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would store beyond the end of the view.
## Examples
### Using setInt8()
```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setInt8(0, 3);
dataview.getInt8(0); // 3
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("Int8Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/setint16/index.md | ---
title: DataView.prototype.setInt16()
slug: Web/JavaScript/Reference/Global_Objects/DataView/setInt16
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.setInt16
---
{{JSRef}}
The **`setInt16()`** method of {{jsxref("DataView")}} instances takes a number and stores it as a 16-bit signed integer in the 2 bytes starting at the specified byte offset of this `DataView`. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.
{{EmbedInteractiveExample("pages/js/dataview-setint16.html")}}
## Syntax
```js-nolint
setInt16(byteOffset, value)
setInt16(byteOffset, value, littleEndian)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to store the data in.
- `value`
- : The value to set. For how the value is encoded in bytes, see [Value encoding and normalization](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#value_encoding_and_normalization).
- `littleEndian` {{optional_inline}}
- : Indicates whether the data is stored in [little- or big-endian](/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written.
### Return value
{{jsxref("undefined")}}.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would store beyond the end of the view.
## Examples
### Using setInt16()
```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setInt16(0, 3);
dataview.getInt16(1); // 768
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("Int16Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/getint16/index.md | ---
title: DataView.prototype.getInt16()
slug: Web/JavaScript/Reference/Global_Objects/DataView/getInt16
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.getInt16
---
{{JSRef}}
The **`getInt16()`** method of {{jsxref("DataView")}} instances reads 2 bytes starting at the specified byte offset of this `DataView` and interprets them as a 16-bit signed integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.
{{EmbedInteractiveExample("pages/js/dataview-getint16.html")}}
## Syntax
```js-nolint
getInt16(byteOffset)
getInt16(byteOffset, littleEndian)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to read the data from.
- `littleEndian` {{optional_inline}}
- : Indicates whether the data is stored in [little- or big-endian](/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read.
### Return value
An integer from -32768 to 32767, inclusive.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would read beyond the end of the view.
## Examples
### Using getInt16()
```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getInt16(1)); // 258
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("Int16Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/getuint16/index.md | ---
title: DataView.prototype.getUint16()
slug: Web/JavaScript/Reference/Global_Objects/DataView/getUint16
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.getUint16
---
{{JSRef}}
The **`getUint16()`** method of {{jsxref("DataView")}} instances reads 2 bytes starting at the specified byte offset of this `DataView` and interprets them as a 16-bit unsigned integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.
{{EmbedInteractiveExample("pages/js/dataview-getuint16.html")}}
## Syntax
```js-nolint
getUint16(byteOffset)
getUint16(byteOffset, littleEndian)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to read the data from.
- `littleEndian` {{optional_inline}}
- : Indicates whether the data is stored in [little- or big-endian](/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read.
### Return value
An integer from 0 to 65535, inclusive.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would read beyond the end of the view.
## Examples
### Using getUint16()
```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getUint16(1)); // 258
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("Uint16Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/getfloat32/index.md | ---
title: DataView.prototype.getFloat32()
slug: Web/JavaScript/Reference/Global_Objects/DataView/getFloat32
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.getFloat32
---
{{JSRef}}
The **`getFloat32()`** method of {{jsxref("DataView")}} instances reads 4 bytes starting at the specified byte offset of this `DataView` and interprets them as a 32-bit floating point number. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.
{{EmbedInteractiveExample("pages/js/dataview-getfloat32.html")}}
## Syntax
```js-nolint
getFloat32(byteOffset)
getFloat32(byteOffset, littleEndian)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to read the data from.
- `littleEndian` {{optional_inline}}
- : Indicates whether the data is stored in [little- or big-endian](/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read.
### Return value
A floating point number from `-3.4e38` to `3.4e38`.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would read beyond the end of the view.
## Examples
### Using getFloat32()
```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getFloat32(1)); // 2.387939260590663e-38
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("Float32Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/getuint8/index.md | ---
title: DataView.prototype.getUint8()
slug: Web/JavaScript/Reference/Global_Objects/DataView/getUint8
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.getUint8
---
{{JSRef}}
The **`getUint8()`** method of {{jsxref("DataView")}} instances reads 1 byte at the specified byte offset of this `DataView` and interprets it as an 8-bit unsigned integer.
{{EmbedInteractiveExample("pages/js/dataview-getuint8.html")}}
## Syntax
```js-nolint
getUint8(byteOffset)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to read the data from.
### Return value
An integer from 0 to 255, inclusive.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would read beyond the end of the view.
## Examples
### Using getUint8()
```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getUint8(1)); // 1
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("Uint8Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/getint32/index.md | ---
title: DataView.prototype.getInt32()
slug: Web/JavaScript/Reference/Global_Objects/DataView/getInt32
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.getInt32
---
{{JSRef}}
The **`getInt32()`** method of {{jsxref("DataView")}} instances reads 4 bytes starting at the specified byte offset of this `DataView` and interprets them as a 32-bit signed integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.
{{EmbedInteractiveExample("pages/js/dataview-getint32.html")}}
## Syntax
```js-nolint
getInt32(byteOffset)
getInt32(byteOffset, littleEndian)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to read the data from.
- `littleEndian` {{optional_inline}}
- : Indicates whether the data is stored in [little- or big-endian](/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read.
### Return value
An integer from -2147483648 to 2147483647, inclusive.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would read beyond the end of the view.
## Examples
### Using getInt32()
```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getInt32(1)); // 16909060
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("Int32Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/setbiguint64/index.md | ---
title: DataView.prototype.setBigUint64()
slug: Web/JavaScript/Reference/Global_Objects/DataView/setBigUint64
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.setBigUint64
---
{{JSRef}}
The **`setBigUint64()`** method of {{jsxref("DataView")}} instances takes a BigInt and stores it as a 64-bit unsigned integer in the 8 bytes starting at the specified byte offset of this `DataView`. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.
{{EmbedInteractiveExample("pages/js/dataview-setbiguint64.html")}}
## Syntax
```js-nolint
setBigUint64(byteOffset, value)
setBigUint64(byteOffset, value, littleEndian)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to store the data in.
- `value`
- : The value to set as a {{jsxref("BigInt")}}. For how the value is encoded in bytes, see [Value encoding and normalization](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#value_encoding_and_normalization).
- `littleEndian` {{optional_inline}}
- : Indicates whether the data is stored in [little- or big-endian](/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written.
### Return value
{{jsxref("undefined")}}.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would store beyond the end of the view.
## Examples
### Using setBigUint64()
```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setBigUint64(0, 3n);
dataview.getBigUint64(1); // 768n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("BigUint64Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/getbigint64/index.md | ---
title: DataView.prototype.getBigInt64()
slug: Web/JavaScript/Reference/Global_Objects/DataView/getBigInt64
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.getBigInt64
---
{{JSRef}}
The **`getBigInt64()`** method of {{jsxref("DataView")}} instances reads 8 bytes starting at the specified byte offset of this `DataView` and interprets them as a 64-bit signed integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.
{{EmbedInteractiveExample("pages/js/dataview-getbigint64.html")}}
## Syntax
```js-nolint
getBigInt64(byteOffset)
getBigInt64(byteOffset, littleEndian)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to read the data from.
- `littleEndian` {{optional_inline}}
- : Indicates whether the data is stored in [little- or big-endian](/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read.
### Return value
A {{jsxref("BigInt")}} from -2<sup>63</sup> to 2<sup>63</sup>-1, inclusive.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would read beyond the end of the view.
## Examples
### Using getBigInt64()
```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getBigInt64(1)); // 72623859790382856n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("BigInt64Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/setint32/index.md | ---
title: DataView.prototype.setInt32()
slug: Web/JavaScript/Reference/Global_Objects/DataView/setInt32
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.setInt32
---
{{JSRef}}
The **`setInt32()`** method of {{jsxref("DataView")}} instances takes a number and stores it as a 32-bit signed integer in the 4 bytes starting at the specified byte offset of this `DataView`. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.
{{EmbedInteractiveExample("pages/js/dataview-setint32.html")}}
## Syntax
```js-nolint
setInt32(byteOffset, value)
setInt32(byteOffset, value, littleEndian)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to store the data in.
- `value`
- : The value to set. For how the value is encoded in bytes, see [Value encoding and normalization](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#value_encoding_and_normalization).
- `littleEndian` {{optional_inline}}
- : Indicates whether the data is stored in [little- or big-endian](/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written.
### Return value
{{jsxref("undefined")}}.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would store beyond the end of the view.
## Examples
### Using setInt32()
```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setInt32(0, 3);
dataview.getInt32(1); // 768
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("Int32Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/getint8/index.md | ---
title: DataView.prototype.getInt8()
slug: Web/JavaScript/Reference/Global_Objects/DataView/getInt8
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.getInt8
---
{{JSRef}}
The **`getInt8()`** method of {{jsxref("DataView")}} instances reads 1 byte at the specified byte offset of this `DataView` and interprets it as an 8-bit signed integer.
{{EmbedInteractiveExample("pages/js/dataview-getint8.html")}}
## Syntax
```js-nolint
getInt8(byteOffset)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to read the data from.
### Return value
An integer from -128 to 127, inclusive.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would read beyond the end of the view.
## Examples
### Using getInt8()
```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getInt8(1)); // 1
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("Int8Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/bytelength/index.md | ---
title: DataView.prototype.byteLength
slug: Web/JavaScript/Reference/Global_Objects/DataView/byteLength
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.DataView.byteLength
---
{{JSRef}}
The **`byteLength`** accessor property of {{jsxref("DataView")}} instances returns the length (in bytes) of this view.
{{EmbedInteractiveExample("pages/js/dataview-bytelength.html")}}
## 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 an `DataView` is constructed and cannot be changed. If the `DataView` is not specifying an offset or a `byteLength`, the `byteLength` of the referenced `ArrayBuffer` or `SharedArrayBuffer` will be returned.
## Examples
### Using the byteLength property
```js
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.byteLength; // 8 (matches the byteLength of the buffer)
const dataview2 = new DataView(buffer, 1, 5);
dataview2.byteLength; // 5 (as specified when constructing the DataView)
const dataview3 = new DataView(buffer, 2);
dataview3.byteLength; // 6 (due to the offset of the constructed DataView)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("SharedArrayBuffer")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/setfloat64/index.md | ---
title: DataView.prototype.setFloat64()
slug: Web/JavaScript/Reference/Global_Objects/DataView/setFloat64
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.setFloat64
---
{{JSRef}}
The **`setFloat64()`** method of {{jsxref("DataView")}} instances takes a number and stores it as a 64-bit floating point number in the 8 bytes starting at the specified byte offset of this `DataView`. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.
{{EmbedInteractiveExample("pages/js/dataview-setfloat64.html")}}
## Syntax
```js-nolint
setFloat64(byteOffset, value)
setFloat64(byteOffset, value, littleEndian)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to store the data in.
- `value`
- : The value to set. For how the value is encoded in bytes, see [Value encoding and normalization](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#value_encoding_and_normalization).
- `littleEndian` {{optional_inline}}
- : Indicates whether the data is stored in [little- or big-endian](/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written.
### Return value
{{jsxref("undefined")}}.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would store beyond the end of the view.
## Examples
### Using setFloat64()
```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setFloat64(0, 3);
dataview.getFloat64(1); // 3.785766995733679e-270
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("Float64Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/dataview/index.md | ---
title: DataView() constructor
slug: Web/JavaScript/Reference/Global_Objects/DataView/DataView
page-type: javascript-constructor
browser-compat: javascript.builtins.DataView.DataView
---
{{JSRef}}
The **`DataView()`** constructor creates {{jsxref("DataView")}} objects.
{{EmbedInteractiveExample("pages/js/dataview-constructor.html")}}
## Syntax
```js-nolint
new DataView(buffer)
new DataView(buffer, byteOffset)
new DataView(buffer, byteOffset, byteLength)
```
> **Note:** `DataView()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
- `buffer`
- : An existing {{jsxref("ArrayBuffer")}} or {{jsxref("SharedArrayBuffer")}} to use as
the storage backing the new `DataView` object.
- `byteOffset` {{optional_inline}}
- : The offset, in bytes, to the first byte in the above buffer for the new view to
reference. If unspecified, the buffer view starts with the first byte.
- `byteLength` {{optional_inline}}
- : The number of elements in the byte array. If unspecified, the view's length will
match the buffer's length.
### Return value
A new {{jsxref("DataView")}} object representing the specified data buffer.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` or `byteLength` parameter values result in the view extending past the end of the buffer. In other words, `byteOffset + byteLength > buffer.byteLength`.
## Examples
### Using DataView
```js
const buffer = new ArrayBuffer(16);
const view = new DataView(buffer, 0);
view.setInt16(1, 42);
view.getInt16(1); // 42
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `DataView` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
- {{jsxref("DataView")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/getuint32/index.md | ---
title: DataView.prototype.getUint32()
slug: Web/JavaScript/Reference/Global_Objects/DataView/getUint32
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.getUint32
---
{{JSRef}}
The **`getUint32()`** method of {{jsxref("DataView")}} instances reads 4 bytes starting at the specified byte offset of this `DataView` and interprets them as a 32-bit unsigned integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.
{{EmbedInteractiveExample("pages/js/dataview-getuint32.html")}}
## Syntax
```js-nolint
getUint32(byteOffset)
getUint32(byteOffset, littleEndian)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to read the data from.
- `littleEndian` {{optional_inline}}
- : Indicates whether the data is stored in [little- or big-endian](/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read.
### Return value
An integer from 0 to 4294967295, inclusive.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would read beyond the end of the view.
## Examples
### Using getUint32()
```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getUint32(1)); // 16909060
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("Uint32Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/setbigint64/index.md | ---
title: DataView.prototype.setBigInt64()
slug: Web/JavaScript/Reference/Global_Objects/DataView/setBigInt64
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.setBigInt64
---
{{JSRef}}
The **`setBigInt64()`** method of {{jsxref("DataView")}} instances takes a BigInt and stores it as a 64-bit signed integer in the 8 bytes starting at the specified byte offset of this `DataView`. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.
{{EmbedInteractiveExample("pages/js/dataview-setbigint64.html")}}
## Syntax
```js-nolint
setBigInt64(byteOffset, value)
setBigInt64(byteOffset, value, littleEndian)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to store the data in.
- `value`
- : The value to set as a {{jsxref("BigInt")}}. For how the value is encoded in bytes, see [Value encoding and normalization](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#value_encoding_and_normalization).
- `littleEndian` {{optional_inline}}
- : Indicates whether the data is stored in [little- or big-endian](/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written.
### Return value
{{jsxref("undefined")}}.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would store beyond the end of the view.
## Examples
### Using setBigInt64()
```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setBigInt64(0, 3n);
dataview.getBigInt64(1); // 768n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("BigInt64Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/setuint16/index.md | ---
title: DataView.prototype.setUint16()
slug: Web/JavaScript/Reference/Global_Objects/DataView/setUint16
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.setUint16
---
{{JSRef}}
The **`setUint16()`** method of {{jsxref("DataView")}} instances takes a number and stores it as a 16-bit unsigned integer in the 2 bytes starting at the specified byte offset of this `DataView`. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.
{{EmbedInteractiveExample("pages/js/dataview-setuint16.html")}}
## Syntax
```js-nolint
setUint16(byteOffset, value)
setUint16(byteOffset, value, littleEndian)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to store the data in.
- `value`
- : The value to set. For how the value is encoded in bytes, see [Value encoding and normalization](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#value_encoding_and_normalization).
- `littleEndian` {{optional_inline}}
- : Indicates whether the data is stored in [little- or big-endian](/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written.
### Return value
{{jsxref("undefined")}}.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would store beyond the end of the view.
## Examples
### Using setUint16()
```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setUint16(0, 3);
dataview.getUint16(1); // 768
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("Uint16Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/getbiguint64/index.md | ---
title: DataView.prototype.getBigUint64()
slug: Web/JavaScript/Reference/Global_Objects/DataView/getBigUint64
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.getBigUint64
---
{{JSRef}}
The **`getBigUint64()`** method of {{jsxref("DataView")}} instances reads 8 bytes starting at the specified byte offset of this `DataView` and interprets them as a 64-bit unsigned integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.
{{EmbedInteractiveExample("pages/js/dataview-getbiguint64.html")}}
## Syntax
```js-nolint
getBigUint64(byteOffset)
getBigUint64(byteOffset, littleEndian)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to read the data from.
- `littleEndian` {{optional_inline}}
- : Indicates whether the data is stored in [little- or big-endian](/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read.
### Return value
A {{jsxref("BigInt")}} from 0 to 2<sup>64</sup>-1, inclusive.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would read beyond the end of the view.
## Examples
### Using getBigUint64()
```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getBigUint64(1)); // 72623859790382856n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("BigUint64Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/getfloat64/index.md | ---
title: DataView.prototype.getFloat64()
slug: Web/JavaScript/Reference/Global_Objects/DataView/getFloat64
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.getFloat64
---
{{JSRef}}
The **`getFloat64()`** method of {{jsxref("DataView")}} instances reads 8 bytes starting at the specified byte offset of this `DataView` and interprets them as a 64-bit floating point number. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.
{{EmbedInteractiveExample("pages/js/dataview-getfloat64.html")}}
## Syntax
```js-nolint
getFloat64(byteOffset)
getFloat64(byteOffset, littleEndian)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to read the data from.
- `littleEndian` {{optional_inline}}
- : Indicates whether the data is stored in [little- or big-endian](/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read.
### Return value
Any number value.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would read beyond the end of the view.
## Examples
### Using getFloat64()
```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getFloat64(1)); // 8.20788039913184e-304
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("Float64Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview | data/mdn-content/files/en-us/web/javascript/reference/global_objects/dataview/setfloat32/index.md | ---
title: DataView.prototype.setFloat32()
slug: Web/JavaScript/Reference/Global_Objects/DataView/setFloat32
page-type: javascript-instance-method
browser-compat: javascript.builtins.DataView.setFloat32
---
{{JSRef}}
The **`setFloat32()`** method of {{jsxref("DataView")}} instances takes a number and stores it as a 32-bit floating point number in the 4 bytes starting at the specified byte offset of this `DataView`. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.
{{EmbedInteractiveExample("pages/js/dataview-setfloat32.html")}}
## Syntax
```js-nolint
setFloat32(byteOffset, value)
setFloat32(byteOffset, value, littleEndian)
```
### Parameters
- `byteOffset`
- : The offset, in bytes, from the start of the view to store the data in.
- `value`
- : The value to set. For how the value is encoded in bytes, see [Value encoding and normalization](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#value_encoding_and_normalization).
- `littleEndian` {{optional_inline}}
- : Indicates whether the data is stored in [little- or big-endian](/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written.
### Return value
{{jsxref("undefined")}}.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `byteOffset` is set such that it would store beyond the end of the view.
## Examples
### Using setFloat32()
```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setFloat32(0, 3);
dataview.getFloat32(1); // 2
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("DataView")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("Float32Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/index.md | ---
title: RegExp
slug: Web/JavaScript/Reference/Global_Objects/RegExp
page-type: javascript-class
browser-compat: javascript.builtins.RegExp
---
{{JSRef}}
The **`RegExp`** object is used for matching text with a pattern.
For an introduction to regular expressions, read the [Regular expressions chapter](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) in the JavaScript guide. For detailed information of regular expression syntax, read the [regular expression reference](/en-US/docs/Web/JavaScript/Reference/Regular_expressions).
## Description
### Literal notation and constructor
There are two ways to create a `RegExp` object: a _literal notation_ and a _constructor_.
- The _literal notation_ takes a pattern between two slashes, followed by optional [flags](/en-US/docs/Web/JavaScript/Guide/Regular_expressions#advanced_searching_with_flags), after the second slash.
- The _constructor function_ takes either a string or a `RegExp` object as its first parameter and a string of optional [flags](/en-US/docs/Web/JavaScript/Guide/Regular_expressions#advanced_searching_with_flags) as its second parameter.
The following three expressions create the same regular expression object:
```js
const re = /ab+c/i; // literal notation
// OR
const re = new RegExp("ab+c", "i"); // constructor with string pattern as first argument
// OR
const re = new RegExp(/ab+c/, "i"); // constructor with regular expression literal as first argument
```
Before regular expressions can be used, they have to be compiled. This process allows them to perform matches more efficiently. More about the process can be found in [dotnet docs](https://docs.microsoft.com/dotnet/standard/base-types/compilation-and-reuse-in-regular-expressions).
The literal notation results in compilation of the regular expression when the expression is evaluated. On the other hand, the constructor of the `RegExp` object, `new RegExp('ab+c')`, results in runtime compilation of the regular expression.
Use a string as the first argument to the `RegExp()` constructor when you want to [build the regular expression from dynamic input](#building_a_regular_expression_from_dynamic_inputs).
### Flags in constructor
The expression `new RegExp(/ab+c/, flags)` will create a new `RegExp` using the source of the first parameter and the [flags](/en-US/docs/Web/JavaScript/Guide/Regular_expressions#advanced_searching_with_flags) provided by the second.
When using the constructor function, the normal string escape rules (preceding special characters with `\` when included in a string) are necessary.
For example, the following are equivalent:
```js
const re = /\w+/;
// OR
const re = new RegExp("\\w+");
```
### Special handling for regexes
> **Note:** Whether something is a "regex" can be [duck-typed](https://en.wikipedia.org/wiki/Duck_typing). It doesn't have to be a `RegExp`!
Some built-in methods would treat regexes specially. They decide whether `x` is a regex through [multiple steps](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-isregexp):
1. `x` must be an object (not a primitive).
2. If [`x[Symbol.match]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/match) is not `undefined`, check if it's [truthy](/en-US/docs/Glossary/Truthy).
3. Otherwise, if `x[Symbol.match]` is `undefined`, check if `x` had been created with the `RegExp` constructor. (This step should rarely happen, since if `x` is a `RegExp` object that have not been tampered with, it should have a `Symbol.match` property.)
Note that in most cases, it would go through the `Symbol.match` check, which means:
- An actual `RegExp` object whose `Symbol.match` property's value is [falsy](/en-US/docs/Glossary/Falsy) but not `undefined` (even with everything else intact, like [`exec`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) and [`@@replace`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace)) can be used as if it's not a regex.
- A non-`RegExp` object with a `Symbol.match` property will be treated as if it's a regex.
This choice was made because `@@match` is the most indicative property that something is intended to be used for matching. (`exec` could also be used, but because it's not a symbol property, there would be too many false positives.) The places that treat regexes specially include:
- [`String.prototype.endsWith()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith), [`startsWith()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith), and [`includes()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes) throw a {{jsxref("TypeError")}} if the first argument is a regex.
- [`String.prototype.matchAll()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll) and [`replaceAll()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) check whether the [global](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global) flag is set if the first argument is a regex before invoking its [`@@matchAll`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/matchAll) or [`@@replace`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/replace) method.
- The [`RegExp()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) constructor directly returns the `pattern` argument only if `pattern` is a regex (among a few other conditions). If `pattern` is a regex, it would also interrogate `pattern`'s `source` and `flags` properties instead of coercing `pattern` to a string.
For example, [`String.prototype.endsWith()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith) would coerce all inputs to strings, but it would throw if the argument is a regex, because it's only designed to match strings, and using a regex is likely a developer mistake.
```js
"foobar".endsWith({ toString: () => "bar" }); // true
"foobar".endsWith(/bar/); // TypeError: First argument to String.prototype.endsWith must not be a regular expression
```
You can get around the check by setting `@@match` to a [falsy](/en-US/docs/Glossary/Falsy) value that's not `undefined`. This would mean that the regex cannot be used for `String.prototype.match()` (since without `@@match`, `match()` would construct a new `RegExp` object with the two enclosing slashes added by [`re.toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/toString)), but it can be used for virtually everything else.
```js
const re = /bar/g;
re[Symbol.match] = false;
"/bar/g".endsWith(re); // true
re.exec("bar"); // [ 'bar', index: 0, input: 'bar', groups: undefined ]
"bar & bar".replace(re, "foo"); // 'foo & foo'
```
### Perl-like RegExp properties
Note that several of the {{jsxref("RegExp")}} properties have both long and short (Perl-like) names. Both names always refer to the same value. (Perl is the programming language from which JavaScript modeled its regular expressions.) See also [deprecated `RegExp` properties](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp).
## Constructor
- {{jsxref("RegExp/RegExp", "RegExp()")}}
- : Creates a new `RegExp` object.
## Static properties
- {{jsxref("RegExp/n", "RegExp.$1, …, RegExp.$9")}} {{deprecated_inline}}
- : Static read-only properties that contain parenthesized substring matches.
- {{jsxref("RegExp/input", "RegExp.input ($_)")}} {{deprecated_inline}}
- : A static property that contains the last string against which a regular expression was successfully matched.
- {{jsxref("RegExp/lastMatch", "RegExp.lastMatch ($&)")}} {{deprecated_inline}}
- : A static read-only property that contains the last matched substring.
- {{jsxref("RegExp/lastParen", "RegExp.lastParen ($+)")}} {{deprecated_inline}}
- : A static read-only property that contains the last parenthesized substring match.
- {{jsxref("RegExp/leftContext", "RegExp.leftContext ($`)")}} {{deprecated_inline}}
- : A static read-only property that contains the substring preceding the most recent match.
- {{jsxref("RegExp/rightContext", "RegExp.rightContext ($')")}} {{deprecated_inline}}
- : A static read-only property that contains the substring following the most recent match.
- {{jsxref("RegExp/@@species", "RegExp[@@species]")}}
- : The constructor function that is used to create derived objects.
## Instance properties
These properties are defined on `RegExp.prototype` and shared by all `RegExp` instances.
- {{jsxref("Object/constructor", "RegExp.prototype.constructor")}}
- : The constructor function that created the instance object. For `RegExp` instances, the initial value is the {{jsxref("RegExp/RegExp", "RegExp")}} constructor.
- {{jsxref("RegExp.prototype.dotAll")}}
- : Whether `.` matches newlines or not.
- {{jsxref("RegExp.prototype.flags")}}
- : A string that contains the flags of the `RegExp` object.
- {{jsxref("RegExp.prototype.global")}}
- : Whether to test the regular expression against all possible matches in a string, or only against the first.
- {{jsxref("RegExp.prototype.hasIndices")}}
- : Whether the regular expression result exposes the start and end indices of captured substrings.
- {{jsxref("RegExp.prototype.ignoreCase")}}
- : Whether to ignore case while attempting a match in a string.
- {{jsxref("RegExp.prototype.multiline")}}
- : Whether or not to search in strings across multiple lines.
- {{jsxref("RegExp.prototype.source")}}
- : The text of the pattern.
- {{jsxref("RegExp.prototype.sticky")}}
- : Whether or not the search is sticky.
- {{jsxref("RegExp.prototype.unicode")}}
- : Whether or not Unicode features are enabled.
- {{jsxref("RegExp.prototype.unicodeSets")}}
- : Whether or not the `v` flag, an upgrade to the `u` mode, is enabled.
These properties are own properties of each `RegExp` instance.
- {{jsxref("RegExp/lastIndex", "lastIndex")}}
- : The index at which to start the next match.
## Instance methods
- {{jsxref("RegExp.prototype.compile()")}} {{deprecated_inline}}
- : (Re-)compiles a regular expression during execution of a script.
- {{jsxref("RegExp.prototype.exec()")}}
- : Executes a search for a match in its string parameter.
- {{jsxref("RegExp.prototype.test()")}}
- : Tests for a match in its string parameter.
- {{jsxref("RegExp.prototype.toString()")}}
- : Returns a string representing the specified object. Overrides the {{jsxref("Object.prototype.toString()")}} method.
- [`RegExp.prototype[@@match]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match)
- : Performs match to given string and returns match result.
- [`RegExp.prototype[@@matchAll]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll)
- : Returns all matches of the regular expression against a string.
- [`RegExp.prototype[@@replace]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace)
- : Replaces matches in given string with new substring.
- [`RegExp.prototype[@@search]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search)
- : Searches the match in given string and returns the index the pattern found in the string.
- [`RegExp.prototype[@@split]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@split)
- : Splits given string into an array by separating the string into substrings.
## Examples
### Using a regular expression to change data format
The following script uses the {{jsxref("String.prototype.replace()")}} method to match a name in the format _first last_ and output it in the format _last, first_.
In the replacement text, the script uses `$1` and `$2` to indicate the results of the corresponding matching parentheses in the regular expression pattern.
```js
const re = /(\w+)\s(\w+)/;
const str = "Maria Cruz";
const newstr = str.replace(re, "$2, $1");
console.log(newstr);
```
This displays `"Cruz, Maria"`.
### Using regular expression to split lines with different line endings/ends of line/line breaks
The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting provided in this example works on all platforms.
```js
const text = "Some text\nAnd some more\r\nAnd yet\rThis is the end";
const lines = text.split(/\r\n|\r|\n/);
console.log(lines); // [ 'Some text', 'And some more', 'And yet', 'This is the end' ]
```
Note that the order of the patterns in the regular expression matters.
### Using regular expression on multiple lines
```js
const s = "Please yes\nmake my day!";
s.match(/yes.*day/);
// Returns null
s.match(/yes[^]*day/);
// Returns ["yes\nmake my day"]
```
### Using a regular expression with the sticky flag
The {{jsxref("RegExp/sticky", "sticky")}} flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at {{jsxref("RegExp.prototype.lastIndex")}}.
```js
const str = "#foo#";
const regex = /foo/y;
regex.lastIndex = 1;
regex.test(str); // true
regex.lastIndex = 5;
regex.test(str); // false (lastIndex is taken into account with sticky flag)
regex.lastIndex; // 0 (reset after match failure)
```
### The difference between the sticky flag and the global flag
With the sticky flag `y`, the next match has to happen at the `lastIndex` position, while with the global flag `g`, the match can happen at the `lastIndex` position or later:
```js
const re = /\d/y;
let r;
while ((r = re.exec("123 456"))) {
console.log(r, "AND re.lastIndex", re.lastIndex);
}
// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1
// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2
// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3
// … and no more match.
```
With the global flag `g`, all 6 digits would be matched, not just 3.
### Regular expression and Unicode characters
`\w` and `\W` only matches ASCII based characters; for example, `a` to `z`, `A` to `Z`, `0` to `9`, and `_`.
To match characters from other languages such as Cyrillic or Hebrew, use `\uhhhh`, where `hhhh` is the character's Unicode value in hexadecimal.
This example demonstrates how one can separate out Unicode characters from a word.
```js
const text = "Образец text на русском языке";
const regex = /[\u0400-\u04FF]+/g;
const match = regex.exec(text);
console.log(match[0]); // 'Образец'
console.log(regex.lastIndex); // 7
const match2 = regex.exec(text);
console.log(match2[0]); // 'на' (did not log 'text')
console.log(regex.lastIndex); // 15
// and so on
```
The [Unicode property escapes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape) feature provides a simpler way to target particular Unicode ranges, by allowing for statements like `\p{scx=Cyrl}` (to match any Cyrillic letter), or `\p{L}/u` (to match a letter from any language).
### Extracting subdomain name from URL
```js
const url = "http://xxx.domain.com";
console.log(/^https?:\/\/(.+?)\./.exec(url)[1]); // 'xxx'
```
> **Note:** Instead of using regular expressions for parsing URLs, it is usually better to use the browsers built-in URL parser by using the [URL API](/en-US/docs/Web/API/URL_API).
### Building a regular expression from dynamic inputs
```js
const breakfasts = ["bacon", "eggs", "oatmeal", "toast", "cereal"];
const order = "Let me get some bacon and eggs, please";
order.match(new RegExp(`\\b(${breakfasts.join("|")})\\b`, "g"));
// Returns ['bacon', 'eggs']
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
### Firefox-specific notes
Starting with Firefox 34, in the case of a capturing group with quantifiers preventing its exercise, the matched text for a capturing group is now `undefined` instead of an empty string:
```js
// Firefox 33 or older
"x".replace(/x(.)?/g, (m, group) => {
console.log(`group: ${JSON.stringify(group)}`);
});
// group: ""
// Firefox 34 or newer
"x".replace(/x(.)?/g, (m, group) => {
console.log(`group: ${group}`);
});
// group: undefined
```
Note that due to web compatibility, `RegExp.$N` will still return an empty string instead of `undefined` ([bug 1053944](https://bugzil.la/1053944)).
## See also
- [Polyfill of many modern `RegExp` features (`dotAll`, `sticky` flags, named capture groups, etc.) in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [Regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- {{jsxref("String.prototype.match()")}}
- {{jsxref("String.prototype.replace()")}}
- {{jsxref("String.prototype.split()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/lastmatch/index.md | ---
title: RegExp.lastMatch ($&)
slug: Web/JavaScript/Reference/Global_Objects/RegExp/lastMatch
page-type: javascript-static-accessor-property
status:
- deprecated
browser-compat: javascript.builtins.RegExp.lastMatch
---
{{JSRef}} {{Deprecated_Header}}
> **Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See [deprecated RegExp features](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp) for more information.
The **`RegExp.lastMatch`** static accessor property returns the last matched substring. `RegExp["$&"]` is an alias for this property.
## Description
Because `lastMatch` is a static property of {{jsxref("RegExp")}}, you always use it as `RegExp.lastMatch` or `RegExp["$&"]`, rather than as a property of a `RegExp` object you created.
The value of `lastMatch` updates whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, `lastMatch` is an empty string. The set accessor of `lastMatch` is `undefined`, so you cannot change this property directly.
You cannot use the shorthand alias with the dot property accessor (`RegExp.$&`), because `&` is not a valid identifier part, so this causes a {{jsxref("SyntaxError")}}. Use the [bracket notation](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) instead.
`$&` can also be used in the replacement string of {{jsxref("String.prototype.replace()")}}, but that's unrelated to the `RegExp["$&"]` legacy property.
## Examples
### Using lastMatch and $&
```js
const re = /hi/g;
re.test("hi there!");
RegExp.lastMatch; // "hi"
RegExp["$&"]; // "hi"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("RegExp/input", "RegExp.input ($_)")}}
- {{jsxref("RegExp/lastParen", "RegExp.lastParen ($+)")}}
- {{jsxref("RegExp/leftContext", "RegExp.leftContext ($`)")}}
- {{jsxref("RegExp/rightContext", "RegExp.rightContext ($')")}}
- {{jsxref("RegExp/n", "RegExp.$1, …, RegExp.$9")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/@@replace/index.md | ---
title: RegExp.prototype[@@replace]()
slug: Web/JavaScript/Reference/Global_Objects/RegExp/@@replace
page-type: javascript-instance-method
browser-compat: javascript.builtins.RegExp.@@replace
---
{{JSRef}}
The **`[@@replace]()`** method of {{jsxref("RegExp")}} instances specifies how [`String.prototype.replace()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) and [`String.prototype.replaceAll()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) should behave when the regular expression is passed in as the pattern.
{{EmbedInteractiveExample("pages/js/regexp-prototype-@@replace.html")}}
## Syntax
```js-nolint
regexp[Symbol.replace](str, replacement)
```
### Parameters
- `str`
- : A {{jsxref("String")}} that is a target of the replacement.
- `replacement`
- : Can be a string or a function.
- If it's a string, it will replace the substring matched by the current regexp. A number of special replacement patterns are supported; see the [Specifying a string as the replacement](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_the_replacement) section of `String.prototype.replace`.
- If it's a function, it will be invoked for every match and the return value is used as the replacement text. The arguments supplied to this function are described in the [Specifying a function as the replacement](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_function_as_the_replacement) section of `String.prototype.replace`.
### Return value
A new string, with one, some, or all matches of the pattern replaced by the specified replacement.
## Description
This method is called internally in {{jsxref("String.prototype.replace()")}} and {{jsxref("String.prototype.replaceAll()")}} if the `pattern` argument is a {{jsxref("RegExp")}} object. For example, the following two examples return the same result.
```js
"abc".replace(/a/, "A");
/a/[Symbol.replace]("abc", "A");
```
If the regex is global (with the `g` flag), the regex's [`exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) method will be repeatedly called until `exec()` returns `null`. Otherwise, `exec()` would only be called once. For each `exec()` result, the substitution will be prepared based on the description in [`String.prototype.replace()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#description).
Because `@@replace` would keep calling `exec()` until it returns `null`, and `exec()` would automatically reset the regex's [`lastIndex`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) to 0 when the last match fails, `@@replace` would typically not have side effects when it exits. However, when the regex is [sticky](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) but not global, `lastIndex` would not be reset. In this case, each call to `replace()` may return a different result.
```js
const re = /a/y;
for (let i = 0; i < 5; i++) {
console.log("aaa".replace(re, "b"), re.lastIndex);
}
// baa 1
// aba 2
// aab 3
// aaa 0
// baa 1
```
When the regex is sticky and global, it would still perform sticky matches — i.e. it would fail to match any occurrences beyond the `lastIndex`.
```js
console.log("aa-a".replace(/a/gy, "b")); // "bb-a"
```
If the current match is an empty string, the `lastIndex` would still be advanced — if the regex is [Unicode-aware](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), it would advance by one Unicode code point; otherwise, it advances by one UTF-16 code unit.
```js
console.log("😄".replace(/(?:)/g, " ")); // " \ud83d \ude04 "
console.log("😄".replace(/(?:)/gu, " ")); // " 😄 "
```
This method exists for customizing replace behavior in `RegExp` subclasses.
## Examples
### Direct call
This method can be used in almost the same way as {{jsxref("String.prototype.replace()")}}, except the different `this` and the different arguments order.
```js
const re = /-/g;
const str = "2016-01-01";
const newstr = re[Symbol.replace](str, ".");
console.log(newstr); // 2016.01.01
```
### Using @@replace in subclasses
Subclasses of {{jsxref("RegExp")}} can override the `[@@replace]()` method to modify the default behavior.
```js
class MyRegExp extends RegExp {
constructor(pattern, flags, count) {
super(pattern, flags);
this.count = count;
}
[Symbol.replace](str, replacement) {
// Perform @@replace |count| times.
let result = str;
for (let i = 0; i < this.count; i++) {
result = RegExp.prototype[Symbol.replace].call(this, result, replacement);
}
return result;
}
}
const re = new MyRegExp("\\d", "", 3);
const str = "01234567";
const newstr = str.replace(re, "#"); // String.prototype.replace calls re[@@replace].
console.log(newstr); // ###34567
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `RegExp.prototype[@@replace]` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.replace()")}}
- {{jsxref("String.prototype.replaceAll()")}}
- [`RegExp.prototype[@@match]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match)
- [`RegExp.prototype[@@matchAll]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll)
- [`RegExp.prototype[@@search]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search)
- [`RegExp.prototype[@@split]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@split)
- {{jsxref("RegExp.prototype.exec()")}}
- {{jsxref("RegExp.prototype.test()")}}
- {{jsxref("Symbol.replace")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/test/index.md | ---
title: RegExp.prototype.test()
slug: Web/JavaScript/Reference/Global_Objects/RegExp/test
page-type: javascript-instance-method
browser-compat: javascript.builtins.RegExp.test
---
{{JSRef}}
The **`test()`** method of {{jsxref("RegExp")}} instances executes a search with this regular expression for a match between a regular expression and a specified string. Returns `true` if there is a match; `false` otherwise.
JavaScript {{jsxref("RegExp")}} objects are **stateful** when they have
the {{jsxref("RegExp/global", "global")}} or {{jsxref("RegExp/sticky", "sticky")}} flags
set (e.g., `/foo/g` or `/foo/y`). They store a
{{jsxref("RegExp/lastIndex", "lastIndex")}} from the previous match. Using this
internally, `test()` can be used to iterate over multiple matches in a string
of text (with capture groups).
{{EmbedInteractiveExample("pages/js/regexp-prototype-test.html", "taller")}}
## Syntax
```js-nolint
test(str)
```
### Parameters
- `str`
- : The string against which to match the regular expression. All values are [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), so omitting it or passing `undefined` causes `test()` to search for the string `"undefined"`, which is rarely what you want.
### Return value
`true` if there is a match between the regular expression and the string
`str`. Otherwise, `false`.
## Description
Use `test()` whenever you want to know whether a pattern is found in a
string. `test()` returns a boolean, unlike the
{{jsxref("String.prototype.search()")}} method (which returns the index of a match, or
`-1` if not found).
To get more information (but with slower execution), use the
{{jsxref("RegExp/exec", "exec()")}} method. (This is similar to the
{{jsxref("String.prototype.match()")}} method.)
As with `exec()` (or in combination with it), `test()` called
multiple times on the same global regular expression instance will advance past the
previous match.
## Examples
### Using test()
Simple example that tests if `"hello"` is contained at the very beginning of
a string, returning a boolean result.
```js
const str = "hello world!";
const result = /^hello/.test(str);
console.log(result); // true
```
The following example logs a message which depends on the success of the test:
```js
function testInput(re, str) {
const midstring = re.test(str) ? "contains" : "does not contain";
console.log(`${str} ${midstring} ${re.source}`);
}
```
### Using test() on a regex with the "global" flag
When a regex has the [global flag](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global) set,
`test()` will advance the {{jsxref("RegExp/lastIndex", "lastIndex")}} of the regex.
({{jsxref("RegExp.prototype.exec()")}} also advances the `lastIndex` property.)
Further calls to `test(str)` will resume searching
`str` starting from `lastIndex`. The
`lastIndex` property will continue to increase each time `test()`
returns `true`.
> **Note:** As long as `test()` returns `true`,
> `lastIndex` will _not_ reset—even when testing a different string!
When `test()` returns `false`, the calling regex's
`lastIndex` property will reset to `0`.
The following example demonstrates this behavior:
```js
const regex = /foo/g; // the "global" flag is set
// regex.lastIndex is at 0
regex.test("foo"); // true
// regex.lastIndex is now at 3
regex.test("foo"); // false
// regex.lastIndex is at 0
regex.test("barfoo"); // true
// regex.lastIndex is at 6
regex.test("foobar"); // false
// regex.lastIndex is at 0
regex.test("foobarfoo"); // true
// regex.lastIndex is at 3
regex.test("foobarfoo"); // true
// regex.lastIndex is at 9
regex.test("foobarfoo"); // false
// regex.lastIndex is at 0
// (...and so on)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) guide
- {{jsxref("RegExp")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/multiline/index.md | ---
title: RegExp.prototype.multiline
slug: Web/JavaScript/Reference/Global_Objects/RegExp/multiline
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.RegExp.multiline
---
{{JSRef}}
The **`multiline`** accessor property of {{jsxref("RegExp")}} instances returns whether or not the `m` flag is used with this regular expression.
{{EmbedInteractiveExample("pages/js/regexp-prototype-multiline.html", "taller")}}
## Description
`RegExp.prototype.multiline` has the value `true` if the `m` flag was used; otherwise, `false`. The `m` flag indicates that a multiline input string should be treated as multiple lines. For example, if `m` is used, `^` and `$` change from matching at only the start or end of the entire string to the start or end of any line within the string.
The set accessor of `multiline` is `undefined`. You cannot change this property directly.
## Examples
### Using multiline
```js
const regex = /foo/m;
console.log(regex.multiline); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("RegExp.prototype.lastIndex")}}
- {{jsxref("RegExp.prototype.dotAll")}}
- {{jsxref("RegExp.prototype.global")}}
- {{jsxref("RegExp.prototype.hasIndices")}}
- {{jsxref("RegExp.prototype.ignoreCase")}}
- {{jsxref("RegExp.prototype.source")}}
- {{jsxref("RegExp.prototype.sticky")}}
- {{jsxref("RegExp.prototype.unicode")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/source/index.md | ---
title: RegExp.prototype.source
slug: Web/JavaScript/Reference/Global_Objects/RegExp/source
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.RegExp.source
---
{{JSRef}}
The **`source`** accessor property of {{jsxref("RegExp")}} instances returns a string containing the source text of this regular expression, without the two forward slashes on both sides or any flags.
{{EmbedInteractiveExample("pages/js/regexp-prototype-source.html")}}
## Description
Conceptually, the `source` property is the text between the two forward slashes in the regular expression literal. The language requires the returned string to be properly escaped, so that when the `source` is concatenated with a forward slash on both ends, it would form a parsable regex literal. For example, for `new RegExp("/")`, the `source` is `\\/`, because if it generates `/`, the resulting literal becomes `///`, which is a line comment. Similarly, all [line terminators](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators) will be escaped because line terminator _characters_ would break up the regex literal. There's no requirement for other characters, as long as the result is parsable. For empty regular expressions, the string `(?:)` is returned.
## Examples
### Using source
```js
const regex = /fooBar/gi;
console.log(regex.source); // "fooBar", doesn't contain /.../ and "gi".
```
### Empty regular expressions and escaping
```js
new RegExp().source; // "(?:)"
new RegExp("\n").source === "\\n"; // true, starting with ES5
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("RegExp.prototype.flags")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/leftcontext/index.md | ---
title: RegExp.leftContext ($`)
slug: Web/JavaScript/Reference/Global_Objects/RegExp/leftContext
page-type: javascript-static-accessor-property
status:
- deprecated
browser-compat: javascript.builtins.RegExp.leftContext
---
{{JSRef}} {{Deprecated_Header}}
> **Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See [deprecated RegExp features](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp) for more information.
The **`RegExp.leftContext`** static accessor property returns the substring preceding the most recent match. ``RegExp["$`"]`` is an alias for this property.
## Description
Because `leftContext` is a static property of {{jsxref("RegExp")}}, you always use it as `RegExp.leftContext` or ``RegExp["$`"]``, rather than as a property of a `RegExp` object you created.
The value of `leftContext` updates whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, `leftContext` is an empty string. The set accessor of `leftContext` is `undefined`, so you cannot change this property directly.
You cannot use the shorthand alias with the dot property accessor (``RegExp.$` ``), because `` ` `` is not a valid identifier part, so this causes a {{jsxref("SyntaxError")}}. Use the [bracket notation](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) instead.
``$` `` can also be used in the replacement string of {{jsxref("String.prototype.replace()")}}, but that's unrelated to the ``RegExp["$`"]`` legacy property.
## Examples
### Using leftContext and $\`
```js
const re = /world/g;
re.test("hello world!");
RegExp.leftContext; // "hello "
RegExp["$`"]; // "hello "
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("RegExp/input", "RegExp.input ($_)")}}
- {{jsxref("RegExp/lastMatch", "RegExp.lastMatch ($&)")}}
- {{jsxref("RegExp/lastParen", "RegExp.lastParen ($+)")}}
- {{jsxref("RegExp/rightContext", "RegExp.rightContext ($')")}}
- {{jsxref("RegExp/n", "RegExp.$1, …, RegExp.$9")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/tostring/index.md | ---
title: RegExp.prototype.toString()
slug: Web/JavaScript/Reference/Global_Objects/RegExp/toString
page-type: javascript-instance-method
browser-compat: javascript.builtins.RegExp.toString
---
{{JSRef}}
The **`toString()`** method of {{jsxref("RegExp")}} instances returns a string representing this regular expression.
{{EmbedInteractiveExample("pages/js/regexp-prototype-tostring.html", "taller")}}
## Syntax
```js-nolint
toString()
```
### Parameters
None.
### Return value
A string representing the given object.
## Description
The {{jsxref("RegExp")}} object overrides the `toString()` method of the {{jsxref("Object")}} object; it does not inherit {{jsxref("Object.prototype.toString()")}}. For {{jsxref("RegExp")}} objects, the `toString()` method returns a string representation of the regular expression.
In practice, it reads the regex's [`source`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source) and [`flags`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) properties and returns a string in the form `/source/flags`. The `toString()` return value is guaranteed to be a parsable regex literal, although it may not be the exact same text as what was originally specified for the regex (for example, the flags may be reordered).
## Examples
### Using toString()
The following example displays the string value of a {{jsxref("RegExp")}} object:
```js
const myExp = new RegExp("a+b+c");
console.log(myExp.toString()); // '/a+b+c/'
const foo = new RegExp("bar", "g");
console.log(foo.toString()); // '/bar/g'
```
### Empty regular expressions and escaping
Since `toString()` accesses the [`source`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source) property, an empty regular expression returns the string `"/(?:)/"`, and line terminators such as `\n` are escaped. This makes the returned value always a valid regex literal.
```js
new RegExp().toString(); // "/(?:)/"
new RegExp("\n").toString() === "/\\n/"; // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Object.prototype.toString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/@@match/index.md | ---
title: RegExp.prototype[@@match]()
slug: Web/JavaScript/Reference/Global_Objects/RegExp/@@match
page-type: javascript-instance-method
browser-compat: javascript.builtins.RegExp.@@match
---
{{JSRef}}
The **`[@@match]()`** method of {{jsxref("RegExp")}} instances specifies how [`String.prototype.match()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) should behave. In addition, its presence (or absence) can influence whether an object is regarded as a regular expression.
{{EmbedInteractiveExample("pages/js/regexp-prototype-@@match.html")}}
## Syntax
```js-nolint
regexp[Symbol.match](str)
```
### Parameters
- `str`
- : A {{jsxref("String")}} that is a target of the match.
### Return value
An {{jsxref("Array")}} whose contents depend on the presence or absence of the global (`g`) flag, or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) if no matches are found.
- If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included.
- If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as {{jsxref("RegExp.prototype.exec()")}} (an array with some extra properties).
## Description
This method is called internally in {{jsxref("String.prototype.match()")}}.
For example, the following two examples return same result.
```js
"abc".match(/a/);
/a/[Symbol.match]("abc");
```
If the regex is global (with the `g` flag), the regex's [`exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) method will be repeatedly called until `exec()` returns `null`. Otherwise, `exec()` would only be called once and its result becomes the return value of `@@match`.
Because `@@match` would keep calling `exec()` until it returns `null`, and `exec()` would automatically reset the regex's [`lastIndex`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) to 0 when the last match fails, `@@match` would typically not have side effects when it exits. However, when the regex is [sticky](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) but not global, `lastIndex` would not be reset. In this case, each call to `match()` may return a different result.
```js
const re = /[abc]/y;
for (let i = 0; i < 5; i++) {
console.log("abc".match(re), re.lastIndex);
}
// [ 'a' ] 1
// [ 'b' ] 2
// [ 'c' ] 3
// null 0
// [ 'a' ] 1
```
When the regex is sticky and global, it would still perform sticky matches — i.e. it would fail to match any occurrences beyond the `lastIndex`.
```js
console.log("ab-c".match(/[abc]/gy)); // [ 'a', 'b' ]
```
If the current match is an empty string, the `lastIndex` would still be advanced — if the regex is [Unicode-aware](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), it would advance by one Unicode code point; otherwise, it advances by one UTF-16 code unit.
```js
console.log("😄".match(/(?:)/g)); // [ '', '', '' ]
console.log("😄".match(/(?:)/gu)); // [ '', '' ]
```
This method exists for customizing match behavior within `RegExp` subclasses.
In addition, the `@@match` property is used to check [whether an object is a regular expression](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes).
## Examples
### Direct call
This method can be used in _almost_ the same way as {{jsxref("String.prototype.match()")}}, except the different `this` and the different arguments order.
```js
const re = /[0-9]+/g;
const str = "2016-01-02";
const result = re[Symbol.match](str);
console.log(result); // ["2016", "01", "02"]
```
### Using @@match in subclasses
Subclasses of {{jsxref("RegExp")}} can override the `[@@match]()` method to modify the default behavior.
```js
class MyRegExp extends RegExp {
[Symbol.match](str) {
const result = RegExp.prototype[Symbol.match].call(this, str);
if (!result) return null;
return {
group(n) {
return result[n];
},
};
}
}
const re = new MyRegExp("([0-9]+)-([0-9]+)-([0-9]+)");
const str = "2016-01-02";
const result = str.match(re); // String.prototype.match calls re[@@match].
console.log(result.group(1)); // 2016
console.log(result.group(2)); // 01
console.log(result.group(3)); // 02
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `RegExp.prototype[@@match]` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.match()")}}
- [`RegExp.prototype[@@matchAll]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll)
- [`RegExp.prototype[@@replace]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace)
- [`RegExp.prototype[@@search]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search)
- [`RegExp.prototype[@@split]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@split)
- {{jsxref("RegExp.prototype.exec()")}}
- {{jsxref("RegExp.prototype.test()")}}
- {{jsxref("Symbol.match")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/hasindices/index.md | ---
title: RegExp.prototype.hasIndices
slug: Web/JavaScript/Reference/Global_Objects/RegExp/hasIndices
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.RegExp.hasIndices
---
{{JSRef}}
The **`hasIndices`** accessor property of {{jsxref("RegExp")}} instances returns whether or not the `d` flag is used with this regular expression.
{{EmbedInteractiveExample("pages/js/regexp-prototype-hasindices.html")}}
## Description
`RegExp.prototype.hasIndices` has the value `true` if the `d` flag was used; otherwise, `false`. The `d` flag indicates that the result of a regular expression match should contain the start and end indices of the substrings of each capture group. It does not change the regex's interpretation or matching behavior in any way, but only provides additional information in the matching result.
This flag primarily affects the return value of [`exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec). If the `d` flag is present, the array returned by `exec()` has an additional `indices` property as described in the `exec()` method's [return value](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec#return_value). Because all other regex-related methods (such as {{jsxref("String.prototype.match()")}}) call `exec()` internally, they will also return the indices if the regex has the `d` flag.
The set accessor of `hasIndices` is `undefined`. You cannot change this property directly.
## Examples
There's a more detailed usage example at [Groups and backreferences > Using groups and match indices](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences#using_groups_and_match_indices).
### Using hasIndices
```js
const str1 = "foo bar foo";
const regex1 = /foo/dg;
console.log(regex1.hasIndices); // true
console.log(regex1.exec(str1).indices[0]); // [0, 3]
console.log(regex1.exec(str1).indices[0]); // [8, 11]
const str2 = "foo bar foo";
const regex2 = /foo/;
console.log(regex2.hasIndices); // false
console.log(regex2.exec(str2).indices); // undefined
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("RegExp.prototype.lastIndex")}}
- {{jsxref("RegExp.prototype.exec()")}}
- {{jsxref("RegExp.prototype.dotAll")}}
- {{jsxref("RegExp.prototype.global")}}
- {{jsxref("RegExp.prototype.ignoreCase")}}
- {{jsxref("RegExp.prototype.multiline")}}
- {{jsxref("RegExp.prototype.source")}}
- {{jsxref("RegExp.prototype.sticky")}}
- {{jsxref("RegExp.prototype.unicode")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/lastindex/index.md | ---
title: "RegExp: lastIndex"
slug: Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex
page-type: javascript-instance-data-property
browser-compat: javascript.builtins.RegExp.lastIndex
---
{{JSRef}}
The **`lastIndex`** data property of a {{jsxref("RegExp")}} instance specifies the index at which to start the next match.
{{EmbedInteractiveExample("pages/js/regexp-lastindex.html")}}
## Value
A non-negative integer.
{{js_property_attributes(1, 0, 0)}}
## Description
This property is set only if the regular expression instance used the `g` flag to indicate a global search, or the `y` flag to indicate a sticky search. The following rules apply when {{jsxref("RegExp/exec", "exec()")}} is called on a given input:
- If `lastIndex` is greater than the length of the input, `exec()` will not find a match, and `lastIndex` will be set to 0.
- If `lastIndex` is equal to or less than the length of the input, `exec()` will attempt to match the input starting from `lastIndex`.
- If `exec()` finds a match, then `lastIndex` will be set to the position of the end of the matched string in the input.
- If `exec()` does not find a match, then `lastIndex` will be set to 0.
Other regex-related methods, such as {{jsxref("RegExp.prototype.test()")}}, {{jsxref("String.prototype.match()")}}, {{jsxref("String.prototype.replace()")}}, etc., call `exec()` under the hood, so they have different effects on `lastIndex`. See their respective pages for details.
## Examples
### Using lastIndex
Consider the following sequence of statements:
```js
const re = /(hi)?/g;
```
Matches the empty string.
```js
console.log(re.exec("hi"));
console.log(re.lastIndex);
```
Returns `["hi", "hi"]` with `lastIndex` equal to 2.
```js
console.log(re.exec("hi"));
console.log(re.lastIndex);
```
Returns `["", undefined]`, an empty array whose zeroth element is the match string. In this case, the empty string because `lastIndex` was 2 (and still is 2) and `hi` has length 2.
### Using lastIndex with sticky regexes
The `lastIndex` property is writable. You can set it to make the regex start its next search at a given index.
The `y` flag almost always requires setting `lastIndex`. It always matches strictly at `lastIndex` and does not attempt any later positions. This is usually useful for writing parsers, when you want to match tokens only at the current position.
```js
const stringPattern = /"[^"]*"/y;
const input = `const message = "Hello world";`;
stringPattern.lastIndex = 6;
console.log(stringPattern.exec(input)); // null
stringPattern.lastIndex = 16;
console.log(stringPattern.exec(input)); // ['"Hello world"']
```
### Rewinding lastIndex
The `g` flag also benefits from setting `lastIndex`. One common use case is when the string is modified in the middle of a global search. In this case, we may miss a particular match if the string is shortened. We can avoid this by rewinding `lastIndex`.
```js
const mdLinkPattern = /\[[^[\]]+\]\((?<link>[^()\s]+)\)/dg;
function resolveMDLink(line) {
let match;
let modifiedLine = line;
while ((match = mdLinkPattern.exec(modifiedLine))) {
const originalLink = match.groups.link;
const resolvedLink = originalLink.replaceAll(/^files|\/index\.md$/g, "");
modifiedLine =
modifiedLine.slice(0, match.indices.groups.link[0]) +
resolvedLink +
modifiedLine.slice(match.indices.groups.link[1]);
// Rewind the pattern to the end of the resolved link
mdLinkPattern.lastIndex += resolvedLink.length - originalLink.length;
}
return modifiedLine;
}
console.log(
resolveMDLink(
"[`lastIndex`](files/en-us/web/javascript/reference/global_objects/regexp/lastindex/index.md)",
),
); // [`lastIndex`](/en-us/web/javascript/reference/global_objects/regexp/lastindex)
console.log(
resolveMDLink(
"[`ServiceWorker`](files/en-us/web/api/serviceworker/index.md) and [`SharedWorker`](files/en-us/web/api/sharedworker/index.md)",
),
); // [`ServiceWorker`](/en-us/web/api/serviceworker) and [`SharedWorker`](/en-us/web/api/sharedworker)
```
Try deleting the `mdLinkPattern.lastIndex += resolvedLink.length - originalLink.length` line and running the second example. You will find that the second link is not replaced correctly, because the `lastIndex` is already past the link's index after the string is shortened.
> **Warning:** This example is for demonstration only. To deal with Markdown, you should probably use a parsing library instead of regex.
### Optimizing searching
You can optimize searching by setting `lastIndex` to a point where previous possible occurrences can be ignored. For example, instead of this:
```js
const stringPattern = /"[^"]*"/g;
const input = `const message = "Hello " + "world";`;
// Pretend we've already dealt with the previous parts of the string
let offset = 26;
const remainingInput = input.slice(offset);
const nextString = stringPattern.exec(remainingInput);
console.log(nextString[0]); // "world"
offset += nextString.index + nextString.length;
```
Consider this:
```js
stringPattern.lastIndex = offset;
const nextString = stringPattern.exec(remainingInput);
console.log(nextString[0]); // "world"
offset = stringPattern.lastIndex;
```
This is potentially more performant because we avoid string slicing.
### Avoiding side effects
The side effects caused by `exec()` can be confusing, especially if the input is different for each `exec()`.
```js
const re = /foo/g;
console.log(re.test("foo bar")); // true
console.log(re.test("foo baz")); // false, because lastIndex is non-zero
```
This is even more confusing when you are hand-modifying `lastIndex`. To contain the side effects, remember to reset `lastIndex` after each input is completely processed.
```js
const re = /foo/g;
console.log(re.test("foo bar")); // true
re.lastIndex = 0;
console.log(re.test("foo baz")); // true
```
With some abstraction, you can require `lastIndex` to be set to a particular value before each `exec()` call.
```js
function createMatcher(pattern) {
// Create a copy, so that the original regex is never updated
const regex = new RegExp(pattern, "g");
return (input, offset) => {
regex.lastIndex = offset;
return regex.exec(input);
};
}
const matchFoo = createMatcher(/foo/);
console.log(matchFoo("foo bar", 0)[0]); // "foo"
console.log(matchFoo("foo baz", 0)[0]); // "foo"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("RegExp.prototype.dotAll")}}
- {{jsxref("RegExp.prototype.global")}}
- {{jsxref("RegExp.prototype.hasIndices")}}
- {{jsxref("RegExp.prototype.ignoreCase")}}
- {{jsxref("RegExp.prototype.multiline")}}
- {{jsxref("RegExp.prototype.source")}}
- {{jsxref("RegExp.prototype.sticky")}}
- {{jsxref("RegExp.prototype.unicode")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/input/index.md | ---
title: RegExp.input ($_)
slug: Web/JavaScript/Reference/Global_Objects/RegExp/input
page-type: javascript-static-accessor-property
status:
- deprecated
browser-compat: javascript.builtins.RegExp.input
---
{{JSRef}} {{Deprecated_Header}}
> **Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See [deprecated RegExp features](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp) for more information.
The **`RegExp.input`** static accessor property returns the string against which a regular expression is matched. `RegExp.$_` is an alias for this property.
## Description
Because `input` is a static property of {{jsxref("RegExp")}}, you always use it as `RegExp.input` or `RegExp.$_`, rather than as a property of a `RegExp` object you created.
The value of `input` updates whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, `input` is an empty string. You can set the value of `input`, but this does not affect other behaviors of the regex, and the value will be overwritten again when the next successful match is made.
## Examples
### Using input and $\_
```js
const re = /hi/g;
re.test("hi there!");
RegExp.input; // "hi there!"
re.test("foo"); // new test, non-matching
RegExp.$_; // "hi there!"
re.test("hi world!"); // new test, matching
RegExp.$_; // "hi world!"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("RegExp/lastMatch", "RegExp.lastMatch ($&)")}}
- {{jsxref("RegExp/lastParen", "RegExp.lastParen ($+)")}}
- {{jsxref("RegExp/leftContext", "RegExp.leftContext ($`)")}}
- {{jsxref("RegExp/rightContext", "RegExp.rightContext ($')")}}
- {{jsxref("RegExp/n", "RegExp.$1, …, RegExp.$9")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/flags/index.md | ---
title: RegExp.prototype.flags
slug: Web/JavaScript/Reference/Global_Objects/RegExp/flags
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.RegExp.flags
---
{{JSRef}}
The **`flags`** accessor property of {{jsxref("RegExp")}} instances returns the [flags](/en-US/docs/Web/JavaScript/Guide/Regular_expressions#advanced_searching_with_flags) of this regular expression.
{{EmbedInteractiveExample("pages/js/regexp-prototype-flags.html")}}
## Description
`RegExp.prototype.flags` has a string as its value. Flags in the `flags` property are sorted alphabetically (from left to right, e.g. `"dgimsuvy"`). It actually invokes the other flag accessors ([`hasIndices`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/hasIndices), [`global`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global), etc.) one-by-one and concatenates the results.
All built-in functions read the `flags` property instead of reading individual flag accessors.
The set accessor of `flags` is `undefined`. You cannot change this property directly.
## Examples
### Using flags
```js-nolint
/foo/ig.flags; // "gi"
/bar/myu.flags; // "muy"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `RegExp.prototype.flags` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [Advanced searching with flags](/en-US/docs/Web/JavaScript/Guide/Regular_expressions#advanced_searching_with_flags) in the Regular expressions guide
- {{jsxref("RegExp.prototype.source")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/@@matchall/index.md | ---
title: RegExp.prototype[@@matchAll]()
slug: Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll
page-type: javascript-instance-method
browser-compat: javascript.builtins.RegExp.@@matchAll
---
{{JSRef}}
The **`[@@matchAll]()`** method of {{jsxref("RegExp")}} instances specifies how [`String.prototype.matchAll`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll) should behave.
{{EmbedInteractiveExample("pages/js/regexp-prototype-@@matchall.html", "taller")}}
## Syntax
```js-nolint
regexp[Symbol.matchAll](str)
```
### Parameters
- `str`
- : A {{jsxref("String")}} that is a target of the match.
### Return value
An [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) (which is not restartable) of matches. Each match is an array with the same shape as the return value of {{jsxref("RegExp.prototype.exec()")}}.
## Description
This method is called internally in {{jsxref("String.prototype.matchAll()")}}. For example, the following two examples return the same result.
```js
"abc".matchAll(/a/g);
/a/g[Symbol.matchAll]("abc");
```
Like [`@@split`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@split), `@@matchAll` starts by using [`@@species`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@species) to construct a new regex, thus avoiding mutating the original regexp in any way. [`lastIndex`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) starts as the original regex's value.
```js
const regexp = /[a-c]/g;
regexp.lastIndex = 1;
const str = "abc";
Array.from(str.matchAll(regexp), (m) => `${regexp.lastIndex} ${m[0]}`);
// [ "1 b", "1 c" ]
```
The validation that the input is a global regex happens in [`String.prototype.matchAll()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll). `@@matchAll` does not validate the input. If the regex is not global, the returned iterator yields the [`exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) result once and then returns `undefined`. If the regexp is global, each time the returned iterator's `next()` method is called, the regex's [`exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) is called and the result is yielded.
When the regex is sticky and global, it will still perform sticky matches — i.e. it will not match any occurrences beyond the `lastIndex`.
```js
console.log(Array.from("ab-c".matchAll(/[abc]/gy)));
// [ [ "a" ], [ "b" ] ]
```
If the current match is an empty string, the [`lastIndex`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) will still be advanced. If the regex has the [`u`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) flag, it advances by one Unicode code point; otherwise, it advances by one UTF-16 code point.
```js
console.log(Array.from("😄".matchAll(/(?:)/g)));
// [ [ "" ], [ "" ], [ "" ] ]
console.log(Array.from("😄".matchAll(/(?:)/gu)));
// [ [ "" ], [ "" ] ]
```
This method exists for customizing the behavior of `matchAll()` in {{jsxref("RegExp")}} subclasses.
## Examples
### Direct call
This method can be used in almost the same way as {{jsxref("String.prototype.matchAll()")}}, except for the different value of `this` and the different order of arguments.
```js
const re = /[0-9]+/g;
const str = "2016-01-02";
const result = re[Symbol.matchAll](str);
console.log(Array.from(result, (x) => x[0]));
// [ "2016", "01", "02" ]
```
### Using @@matchAll in subclasses
Subclasses of {{jsxref("RegExp")}} can override the `[@@matchAll]()` method to modify the default behavior.
For example, to return an {{jsxref("Array")}} instead of an [iterator](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators):
```js
class MyRegExp extends RegExp {
[Symbol.matchAll](str) {
const result = RegExp.prototype[Symbol.matchAll].call(this, str);
return result ? Array.from(result) : null;
}
}
const re = new MyRegExp("([0-9]+)-([0-9]+)-([0-9]+)", "g");
const str = "2016-01-02|2019-03-07";
const result = str.matchAll(re);
console.log(result[0]);
// [ "2016-01-02", "2016", "01", "02" ]
console.log(result[1]);
// [ "2019-03-07", "2019", "03", "07" ]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `RegExp.prototype[@@matchAll]` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.matchAll()")}}
- [`RegExp.prototype[@@match]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match)
- [`RegExp.prototype[@@replace]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace)
- [`RegExp.prototype[@@search]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search)
- [`RegExp.prototype[@@split]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@split)
- {{jsxref("Symbol.matchAll")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/lastparen/index.md | ---
title: RegExp.lastParen ($+)
slug: Web/JavaScript/Reference/Global_Objects/RegExp/lastParen
page-type: javascript-static-accessor-property
status:
- deprecated
browser-compat: javascript.builtins.RegExp.lastParen
---
{{JSRef}} {{Deprecated_Header}}
> **Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See [deprecated RegExp features](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp) for more information.
The **`RegExp.lastParen`** static accessor property returns the last parenthesized substring match, if any. `RegExp["$+"]` is an alias for this property.
## Description
Because `lastParen` is a static property of {{jsxref("RegExp")}}, you always use it as `RegExp.lastParen` or `RegExp["$+"]`, rather than as a property of a `RegExp` object you created.
The value of `lastParen` updates whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, or if the most recent regex execution contains no capturing groups, `lastParen` is an empty string. The set accessor of `lastParen` is `undefined`, so you cannot change this property directly.
You cannot use the shorthand alias with the dot property accessor (`RegExp.$+`), because `+` is not a valid identifier part, so this causes a {{jsxref("SyntaxError")}}. Use the [bracket notation](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) instead.
## Examples
### Using lastParen and $+
```js
const re = /(hi)/g;
re.test("hi there!");
RegExp.lastParen; // "hi"
RegExp["$+"]; // "hi"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("RegExp/input", "RegExp.input ($_)")}}
- {{jsxref("RegExp/lastMatch", "RegExp.lastMatch ($&)")}}
- {{jsxref("RegExp/leftContext", "RegExp.leftContext ($`)")}}
- {{jsxref("RegExp/rightContext", "RegExp.rightContext ($')")}}
- {{jsxref("RegExp/n", "RegExp.$1, …, RegExp.$9")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/exec/index.md | ---
title: RegExp.prototype.exec()
slug: Web/JavaScript/Reference/Global_Objects/RegExp/exec
page-type: javascript-instance-method
browser-compat: javascript.builtins.RegExp.exec
---
{{JSRef}}
The **`exec()`** method of {{jsxref("RegExp")}} instances executes a search with this regular expression for a match in a specified string and returns a result array, or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null).
{{EmbedInteractiveExample("pages/js/regexp-prototype-exec.html")}}
## Syntax
```js-nolint
exec(str)
```
### Parameters
- `str`
- : The string against which to match the regular expression. All values are [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), so omitting it or passing `undefined` causes `exec()` to search for the string `"undefined"`, which is rarely what you want.
### Return value
If the match fails, the `exec()` method returns [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null), and sets the regex's [`lastIndex`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) to `0`.
If the match succeeds, the `exec()` method returns an array and updates the [`lastIndex`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) property of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing group of the matched text. The array also has the following additional properties:
- `index`
- : The 0-based index of the match in the string.
- `input`
- : The original string that was matched against.
- `groups`
- : A [`null`-prototype object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) of named capturing groups, whose keys are the names, and values are the capturing groups, or {{jsxref("undefined")}} if no named capturing groups were defined. See [capturing groups](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences) for more information.
- `indices` {{optional_inline}}
- : This property is only present when the [`d`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/hasIndices) flag is set. It is an array where each entry represents the bounds of a substring match. The index of each element in this array corresponds to the index of the respective substring match in the array returned by `exec()`. In other words, the first `indices` entry represents the entire match, the second `indices` entry represents the first capturing group, etc. Each entry itself is a two-element array, where the first number represents the match's start index, and the second number, its end index.
The `indices` array additionally has a `groups` property, which holds a [`null`-prototype object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) of all named capturing groups. The keys are the names of the capturing groups, and each value is a two-element array, with the first number being the start index, and the second number being the end index of the capturing group. If the regular expression doesn't contain any named capturing groups, `groups` is `undefined`.
## Description
JavaScript {{jsxref("RegExp")}} objects are _stateful_ when they have the [global](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global) or [sticky](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flags set (e.g. `/foo/g` or `/foo/y`). They store a [`lastIndex`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) from the previous match. Using this internally, `exec()` can be used to iterate over multiple matches in a string of text (with capture groups), as opposed to getting just the matching strings with {{jsxref("String.prototype.match()")}}.
When using `exec()`, the global flag has no effect when the sticky flag is set — the match is always sticky.
`exec()` is the primitive method of regexps. Many other regexp methods call `exec()` internally — including those called by string methods, like [`@@replace`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). While `exec()` itself is powerful (and is the most efficient), it often does not convey the intent most clearly.
- If you only care whether the regex matches a string, but not what is actually being matched, use {{jsxref("RegExp.prototype.test()")}} instead.
- If you are finding all occurrences of a global regex and you don't care about information like capturing groups, use {{jsxref("String.prototype.match()")}} instead. In addition, {{jsxref("String.prototype.matchAll()")}} helps to simplify matching multiple parts of a string (with capture groups) by allowing you to iterate over the matches.
- If you are executing a match to find its index position in the string, use the {{jsxref("String.prototype.search()")}} method instead.
## Examples
### Using exec()
Consider the following example:
```js
// Match "quick brown" followed by "jumps", ignoring characters in between
// Remember "brown" and "jumps"
// Ignore case
const re = /quick\s(?<color>brown).+?(jumps)/dgi;
const result = re.exec("The Quick Brown Fox Jumps Over The Lazy Dog");
```
The following table shows the state of `result` after running this script:
| Property | Value |
| --------- | ------------------------------------------------------------------ |
| `[0]` | `"Quick Brown Fox Jumps"` |
| `[1]` | `"Brown"` |
| `[2]` | `"Jumps"` |
| `index` | `4` |
| `indices` | `[[4, 25], [10, 15], [20, 25]]`<br />`groups: { color: [10, 15 ]}` |
| `input` | `"The Quick Brown Fox Jumps Over The Lazy Dog"` |
| `groups` | `{ color: "brown" }` |
In addition, `re.lastIndex` will be set to `25`, due to this regex being global.
### Finding successive matches
If your regular expression uses the [`g`](/en-US/docs/Web/JavaScript/Guide/Regular_expressions#advanced_searching_with_flags) flag, you can use the `exec()` method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of `str` specified by the regular expression's {{jsxref("RegExp/lastIndex", "lastIndex")}} property ({{jsxref("RegExp/test", "test()")}} will also advance the {{jsxref("RegExp/lastIndex", "lastIndex")}} property). Note that the {{jsxref("RegExp/lastIndex", "lastIndex")}} property will not be reset when searching a different string, it will start its search at its existing {{jsxref("RegExp/lastIndex", "lastIndex")}}.
For example, assume you have this script:
```js
const myRe = /ab*/g;
const str = "abbcdefabh";
let myArray;
while ((myArray = myRe.exec(str)) !== null) {
let msg = `Found ${myArray[0]}. `;
msg += `Next match starts at ${myRe.lastIndex}`;
console.log(msg);
}
```
This script displays the following text:
```plain
Found abb. Next match starts at 3
Found ab. Next match starts at 9
```
> **Warning:** There are many pitfalls that can lead to this becoming an infinite loop!
>
> - Do _not_ place the regular expression literal (or {{jsxref("RegExp")}} constructor) within the `while` condition — it will recreate the regex for every iteration and reset {{jsxref("RegExp/lastIndex", "lastIndex")}}.
> - Be sure that the [global (`g`) flag](/en-US/docs/Web/JavaScript/Guide/Regular_expressions#advanced_searching_with_flags) is set, or `lastIndex` will never be advanced.
> - If the regex may match zero-length characters (e.g. `/^/gm`), increase its {{jsxref("RegExp/lastIndex", "lastIndex")}} manually each time to avoid being stuck in the same place.
You can usually replace this kind of code with {{jsxref("String.prototype.matchAll()")}} to make it less error-prone.
### Using exec() with RegExp literals
You can also use `exec()` without creating a {{jsxref("RegExp")}} object
explicitly:
```js
const matches = /(hello \S+)/.exec("This is a hello world!");
console.log(matches[1]);
```
This will log a message containing `'hello world!'`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) guide
- {{jsxref("RegExp")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/dotall/index.md | ---
title: RegExp.prototype.dotAll
slug: Web/JavaScript/Reference/Global_Objects/RegExp/dotAll
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.RegExp.dotAll
---
{{JSRef}}
The **`dotAll`** accessor property of {{jsxref("RegExp")}} instances returns whether or not the `s` flag is used with this regular expression.
{{EmbedInteractiveExample("pages/js/regexp-prototype-dotall.html")}}
## Description
`RegExp.prototype.dotAll` has the value `true` if the `s` flag was used; otherwise, `false`. The `s` flag indicates that the dot special character (`.`) should additionally match the following line terminator ("newline") characters in a string, which it would not match otherwise:
- U+000A LINE FEED (LF) (`\n`)
- U+000D CARRIAGE RETURN (CR) (`\r`)
- U+2028 LINE SEPARATOR
- U+2029 PARAGRAPH SEPARATOR
This effectively means the dot will match any character on the Unicode Basic Multilingual Plane (BMP). To allow it to match astral characters, the `u` (unicode) flag should be used. Using both flags in conjunction allows the dot to match any Unicode character, without exceptions.
The set accessor of `dotAll` is `undefined`. You cannot change this property directly.
## Examples
### Using dotAll
```js
const str1 = "bar\nexample foo example";
const regex1 = /bar.example/s;
console.log(regex1.dotAll); // true
console.log(str1.replace(regex1, "")); // foo example
const str2 = "bar\nexample foo example";
const regex2 = /bar.example/;
console.log(regex2.dotAll); // false
console.log(str2.replace(regex2, ""));
// bar
// example foo example
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of the `dotAll` flag in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("RegExp.prototype.lastIndex")}}
- {{jsxref("RegExp.prototype.global")}}
- {{jsxref("RegExp.prototype.hasIndices")}}
- {{jsxref("RegExp.prototype.ignoreCase")}}
- {{jsxref("RegExp.prototype.multiline")}}
- {{jsxref("RegExp.prototype.source")}}
- {{jsxref("RegExp.prototype.sticky")}}
- {{jsxref("RegExp.prototype.unicode")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/n/index.md | ---
title: RegExp.$1, …, RegExp.$9
slug: Web/JavaScript/Reference/Global_Objects/RegExp/n
page-type: javascript-static-accessor-property
status:
- deprecated
browser-compat: javascript.builtins.RegExp.n
---
{{JSRef}} {{Deprecated_Header}}
> **Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See [deprecated RegExp features](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp) for more information.
The **`RegExp.$1, …, RegExp.$9`** static accessor properties return parenthesized substring matches.
## Description
Because `$1`–`$9` are static properties of {{jsxref("RegExp")}}, you always use them as `RegExp.$1`, `RegExp.$2`, etc., rather than as properties of a `RegExp` object you created.
The values of `$1, …, $9` update whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, or if the last match does not have the corresponding capturing group, the respective property is an empty string. The set accessor of each property is `undefined`, so you cannot change the properties directly.
The number of possible parenthesized substrings is unlimited, but the `RegExp` object can only hold the first nine. You can access all parenthesized substrings through the returned array's indexes.
`$1, …, $9` can also be used in the replacement string of {{jsxref("String.prototype.replace()")}}, but that's unrelated to the `RegExp.$n` legacy properties.
## Examples
### Using $n with RegExp.prototype.test()
The following script uses the {{jsxref("RegExp.prototype.test()")}} method to grab a number in a generic string.
```js
const str = "Test 24";
const number = /(\d+)/.test(str) ? RegExp.$1 : "0";
number; // "24"
```
Please note that any operation involving the usage of other regular expressions between a `re.test(str)` call and the `RegExp.$n` property, might have side effects, so that accessing these special properties should be done instantly, otherwise the result might be unexpected.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("RegExp/input", "RegExp.input ($_)")}}
- {{jsxref("RegExp/lastMatch", "RegExp.lastMatch ($&)")}}
- {{jsxref("RegExp/lastParen", "RegExp.lastParen ($+)")}}
- {{jsxref("RegExp/leftContext", "RegExp.leftContext ($`)")}}
- {{jsxref("RegExp/rightContext", "RegExp.rightContext ($')")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/ignorecase/index.md | ---
title: RegExp.prototype.ignoreCase
slug: Web/JavaScript/Reference/Global_Objects/RegExp/ignoreCase
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.RegExp.ignoreCase
---
{{JSRef}}
The **`ignoreCase`** accessor property of {{jsxref("RegExp")}} instances returns whether or not the `i` flag is used with this regular expression.
{{EmbedInteractiveExample("pages/js/regexp-prototype-ignorecase.html")}}
## Description
`RegExp.prototype.ignoreCase` has the value `true` if the `i` flag was used; otherwise, `false`. The `i` flag indicates that case should be ignored while attempting a match in a string. Case-insensitive matching is done by mapping both the expected character set and the matched string to the same casing.
If the regex is [Unicode-aware](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), the case mapping happens through _simple case folding_ specified in [`CaseFolding.txt`](https://unicode.org/Public/UCD/latest/ucd/CaseFolding.txt). The mapping always maps to a single code point, so it does not map, for example, `ß` (U+00DF LATIN SMALL LETTER SHARP S) to `ss` (which is _full case folding_, not _simple case folding_). It may however map code points outside the Basic Latin block to code points within it — for example, `ſ` (U+017F LATIN SMALL LETTER LONG S) case-folds to `s` (U+0073 LATIN SMALL LETTER S) and `K` (U+212A KELVIN SIGN) case-folds to `k` (U+006B LATIN SMALL LETTER K). Therefore, `ſ` and `K` can be matched by `/[a-z]/ui`.
If the regex is Unicode-unaware, case mapping uses the [Unicode Default Case Conversion](https://unicode-org.github.io/icu/userguide/transforms/casemappings.html) — the same algorithm used in {{jsxref("String.prototype.toUpperCase()")}}. For example, `Ω` (U+2126 OHM SIGN) and `Ω` (U+03A9 GREEK CAPITAL LETTER OMEGA) are both mapped by Default Case Conversion to themselves but by simple case folding to `ω` (U+03C9 GREEK SMALL LETTER OMEGA), so `"ω"` is matched by `/[\u2126]/ui` and `/[\u03a9]/ui` but not by `/[\u2126]/i` or `/[\u03a9]/i`. This algorithm prevents code points outside the Basic Latin block to be mapped to code points within it, so `ſ` and `K` mentioned previously are not matched by `/[a-z]/i`.
The set accessor of `ignoreCase` is `undefined`. You cannot change this property directly.
## Examples
### Using ignoreCase
```js
const regex = /foo/i;
console.log(regex.ignoreCase); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("RegExp.prototype.lastIndex")}}
- {{jsxref("RegExp.prototype.dotAll")}}
- {{jsxref("RegExp.prototype.global")}}
- {{jsxref("RegExp.prototype.hasIndices")}}
- {{jsxref("RegExp.prototype.multiline")}}
- {{jsxref("RegExp.prototype.source")}}
- {{jsxref("RegExp.prototype.sticky")}}
- {{jsxref("RegExp.prototype.unicode")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/regexp/index.md | ---
title: RegExp() constructor
slug: Web/JavaScript/Reference/Global_Objects/RegExp/RegExp
page-type: javascript-constructor
browser-compat: javascript.builtins.RegExp.RegExp
---
{{JSRef}}
The **`RegExp()`** constructor creates {{jsxref("RegExp")}} objects.
For an introduction to regular expressions, read the [Regular Expressions chapter](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) in the [JavaScript Guide](/en-US/docs/Web/JavaScript/Guide).
{{EmbedInteractiveExample("pages/js/regexp-constructor.html")}}
## Syntax
```js-nolint
new RegExp(pattern)
new RegExp(pattern, flags)
RegExp(pattern)
RegExp(pattern, flags)
```
> **Note:** `RegExp()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new), but sometimes with different effects. See [Return value](#return_value).
### Parameters
- `pattern`
- : The text of the regular expression. This can also be another `RegExp` object.
- `flags` {{optional_inline}}
- : If specified, `flags` is a string that contains the flags to add. Alternatively, if a `RegExp` object is supplied for the `pattern`, the `flags` string will replace any of that object's flags (and `lastIndex` will be reset to `0`).
`flags` may contain any combination of the following characters:
- [`d` (indices)](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/hasIndices)
- : Generate indices for substring matches.
- [`g` (global)](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global)
- : Find all matches rather than stopping after the first match.
- [`i` (ignore case)](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/ignoreCase)
- : When matching, casing differences are ignored.
- [`m` (multiline)](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/multiline)
- : Treat beginning and end assertions (`^` and `$`) as working over multiple lines. In other words, match the beginning or end of _each_ line (delimited by `\n` or `\r`), not only the very beginning or end of the whole input string.
- [`s` (dotAll)](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/dotAll)
- : Allows `.` to match newlines.
- [`u` (unicode)](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode)
- : Treat `pattern` as a sequence of Unicode code points.
- [`v` (unicodeSets)](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicodeSets)
- : An upgrade to the `u` flag that enables set notation in character classes as well as properties of strings.
- [`y` (sticky)](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky)
- : Matches only from the index indicated by the `lastIndex` property of this regular expression in the target string. Does not attempt to match from any later indexes.
### Return value
`RegExp(pattern)` returns `pattern` directly if all of the following are true:
- `RegExp()` is called without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new);
- [`pattern` is a regex](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes);
- `pattern.constructor === RegExp` (usually meaning it's not a subclass);
- `flags` is `undefined`.
In all other cases, calling `RegExp()` with or without `new` both create a new `RegExp` object. If `pattern` is a regex, the new object's [source](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source) is `pattern.source`; otherwise, its source is `pattern` [coerced to a string](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the `flags` parameter is not `undefined`, the new object's [`flags`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) is the parameter's value; otherwise, its `flags` is `pattern.flags` (if `pattern` is a regex).
### Exceptions
- {{jsxref("SyntaxError")}}
- : Thrown in one of the following cases:
- `pattern` cannot be parsed as a valid regular expression.
- `flags` contains repeated characters or any character outside of those allowed.
## Examples
### Literal notation and constructor
There are two ways to create a `RegExp` object: a _literal notation_ and a _constructor_.
- The _literal notation_ takes a pattern between two slashes, followed by optional flags, after the second slash.
- The _constructor function_ takes either a string or a `RegExp` object as its first parameter and a string of optional flags as its second parameter.
The following three expressions create the same regular expression:
```js
/ab+c/i;
new RegExp(/ab+c/, "i"); // literal notation
new RegExp("ab+c", "i"); // constructor
```
Before regular expressions can be used, they have to be compiled. This process allows them to perform matches more efficiently. There are two ways to compile and get a `RegExp` object.
The literal notation results in compilation of the regular expression when the expression is evaluated. On the other hand, the constructor of the `RegExp` object, `new RegExp('ab+c')`, results in runtime compilation of the regular expression.
Use a string as the first argument to the `RegExp()` constructor when you want to [build the regular expression from dynamic input](#building_a_regular_expression_from_dynamic_inputs).
### Building a regular expression from dynamic inputs
```js
const breakfasts = ["bacon", "eggs", "oatmeal", "toast", "cereal"];
const order = "Let me get some bacon and eggs, please";
order.match(new RegExp(`\\b(${breakfasts.join("|")})\\b`, "g"));
// Returns ['bacon', 'eggs']
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of many modern `RegExp` features (`dotAll`, `sticky` flags, named capture groups, etc.) in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [Regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) guide
- {{jsxref("String.prototype.match()")}}
- {{jsxref("String.prototype.replace()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/unicode/index.md | ---
title: RegExp.prototype.unicode
slug: Web/JavaScript/Reference/Global_Objects/RegExp/unicode
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.RegExp.unicode
---
{{JSRef}}
The **`unicode`** accessor property of {{jsxref("RegExp")}} instances returns whether or not the `u` flag is used with this regular expression.
{{EmbedInteractiveExample("pages/js/regexp-prototype-unicode.html", "taller")}}
## Description
`RegExp.prototype.unicode` has the value `true` if the `u` flag was used; otherwise, `false`. The `u` flag enables various Unicode-related features. With the "u" flag:
- Any [Unicode code point escapes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape) (`\u{xxxx}`, `\p{UnicodePropertyValue}`) will be interpreted as such instead of identity escapes. For example `/\u{61}/u` matches `"a"`, but `/\u{61}/` (without `u` flag) matches `"u".repeat(61)`, where the `\u` is equivalent to a single `u`.
- Surrogate pairs will be interpreted as whole characters instead of two separate characters. For example, `/[😄]/u` would only match `"😄"` but not `"\ud83d"`.
- When [`lastIndex`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) is automatically advanced (such as when calling [`exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec)), unicode regexes advance by Unicode code points instead of UTF-16 code units.
There are other changes to the parsing behavior that prevent possible syntax mistakes (which are analogous to [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) for regex syntax). These syntaxes are all [deprecated and only kept for web compatibility](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp), and you should not rely on them.
The set accessor of `unicode` is `undefined`. You cannot change this property directly.
### Unicode-aware mode
When we refer to _Unicode-aware mode_, we mean the regex has either the `u` or the [`v`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicodeSets) flag, in which case the regex enables Unicode-related features (such as [Unicode character class escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape)) and has much stricter syntax rules. Because `u` and `v` interpret the same regex in incompatible ways, using both flags results in a {{jsxref("SyntaxError")}}.
Similarly, a regex is _Unicode-unaware_ if it has neither the `u` nor the `v` flag. In this case, the regex is interpreted as a sequence of UTF-16 code units, and there are many legacy syntaxes that do not become syntax errors.
## Examples
### Using the unicode property
```js
const regex = /\u{61}/u;
console.log(regex.unicode); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("RegExp.prototype.lastIndex")}}
- {{jsxref("RegExp.prototype.dotAll")}}
- {{jsxref("RegExp.prototype.global")}}
- {{jsxref("RegExp.prototype.hasIndices")}}
- {{jsxref("RegExp.prototype.ignoreCase")}}
- {{jsxref("RegExp.prototype.multiline")}}
- {{jsxref("RegExp.prototype.source")}}
- {{jsxref("RegExp.prototype.sticky")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/sticky/index.md | ---
title: RegExp.prototype.sticky
slug: Web/JavaScript/Reference/Global_Objects/RegExp/sticky
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.RegExp.sticky
---
{{JSRef}}
The **`sticky`** accessor property of {{jsxref("RegExp")}} instances returns whether or not the `y` flag is used with this regular expression.
{{EmbedInteractiveExample("pages/js/regexp-prototype-sticky.html", "taller")}}
## Description
`RegExp.prototype.sticky` has the value `true` if the `y` flag was used; otherwise, `false`. The `y` flag indicates that the regex attempts to match the target string only from the index indicated by the {{jsxref("RegExp/lastIndex", "lastIndex")}} property (and unlike a global regex, does not attempt to match from any later indexes).
The set accessor of `sticky` is `undefined`. You cannot change this property directly.
For both sticky regexes and [global](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global) regexes:
- They start matching at `lastIndex`.
- When the match succeeds, `lastIndex` is advanced to the end of the match.
- When `lastIndex` is out of bounds of the currently matched string, `lastIndex` is reset to 0.
However, for the [`exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) method, the behavior when matching fails is different:
- When the [`exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) method is called on a sticky regex, if the regex fails to match at `lastIndex`, the regex immediately returns `null` and resets `lastIndex` to 0.
- When the [`exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) method is called on a global regex, if the regex fails to match at `lastIndex`, it tries to match from the next character, and so on until a match is found or the end of the string is reached.
For the [`exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) method, a regex that's both sticky and global behaves the same as a sticky and non-global regex. Because [`test()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) is a simple wrapper around `exec()`, `test()` would ignore the global flag and perform sticky matches as well. However, due to many other methods special-casing the behavior of global regexes, the global flag is, in general, orthogonal to the sticky flag.
- [`String.prototype.matchAll()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll) (which calls [`RegExp.prototype[@@matchAll]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll)): `y`, `g` and `gy` are all different.
- For `y` regexes: `matchAll()` throws; `[@@matchAll]()` yields the `exec()` result exactly once, without updating the regex's `lastIndex`.
- For `g` or `gy` regexes: returns an iterator that yields a sequence of `exec()` results.
- [`String.prototype.match()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) (which calls [`RegExp.prototype[@@match]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match)): `y`, `g` and `gy` are all different.
- For `y` regexes: returns the `exec()` result and updates the regex's `lastIndex`.
- For `g` or `gy` regexes: returns an array of all `exec()` results.
- [`String.prototype.search()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search) (which calls [`RegExp.prototype[@@search]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search)): the `g` flag is always irrelevant.
- For `y` or `gy` regexes: always returns `0` (if the very beginning of the string matches) or `-1` (if the beginning doesn't match), without updating the regex's `lastIndex` when it exits.
- For `g` regexes: returns the index of the first match in the string, or `-1` if no match is found.
- [`String.prototype.split()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) (which calls [`RegExp.prototype[@@split]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@split)): `y`, `g`, and `gy` all have the same behavior.
- [`String.prototype.replace()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) (which calls [`RegExp.prototype[@@replace]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace)): `y`, `g` and `gy` are all different.
- For `y` regexes: replaces once at the current `lastIndex` and updates `lastIndex`.
- For `g` and `gy` regexes: replaces all occurrences matched by `exec()`.
- [`String.prototype.replaceAll()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) (which calls [`RegExp.prototype[@@replace]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace)): `y`, `g` and `gy` are all different.
- For `y` regexes: `replaceAll()` throws.
- For `g` and `gy` regexes: replaces all occurrences matched by `exec()`.
## Examples
### Using a regular expression with the sticky flag
```js
const str = "#foo#";
const regex = /foo/y;
regex.lastIndex = 1;
regex.test(str); // true
regex.lastIndex = 5;
regex.test(str); // false (lastIndex is taken into account with sticky flag)
regex.lastIndex; // 0 (reset after match failure)
```
### Anchored sticky flag
For several versions, Firefox's SpiderMonkey engine had [a bug](https://bugzil.la/773687) with regard to the `^` assertion and the sticky flag which allowed expressions starting with the `^` assertion and using the sticky flag to match when they shouldn't. The bug was introduced some time after Firefox 3.6 (which had the sticky flag but not the bug) and fixed in 2015. Perhaps because of the bug, the specification [specifically calls out](https://tc39.es/ecma262/multipage/text-processing.html#sec-compileassertion) the fact that:
> Even when the `y` flag is used with a pattern, `^` always matches only at the beginning of _Input_, or (if _rer_.[[Multiline]] is `true`) at the beginning of a line.
Examples of correct behavior:
```js
const regex = /^foo/y;
regex.lastIndex = 2;
regex.test("..foo"); // false - index 2 is not the beginning of the string
const regex2 = /^foo/my;
regex2.lastIndex = 2;
regex2.test("..foo"); // false - index 2 is not the beginning of the string or line
regex2.lastIndex = 2;
regex2.test(".\nfoo"); // true - index 2 is the beginning of a line
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of the `sticky` flag in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("RegExp.prototype.lastIndex")}}
- {{jsxref("RegExp.prototype.dotAll")}}
- {{jsxref("RegExp.prototype.global")}}
- {{jsxref("RegExp.prototype.hasIndices")}}
- {{jsxref("RegExp.prototype.ignoreCase")}}
- {{jsxref("RegExp.prototype.multiline")}}
- {{jsxref("RegExp.prototype.source")}}
- {{jsxref("RegExp.prototype.unicode")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/global/index.md | ---
title: RegExp.prototype.global
slug: Web/JavaScript/Reference/Global_Objects/RegExp/global
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.RegExp.global
---
{{JSRef}}
The **`global`** accessor property of {{jsxref("RegExp")}} instances returns whether or not the `g` flag is used with this regular expression.
{{EmbedInteractiveExample("pages/js/regexp-prototype-global.html")}}
## Description
`RegExp.prototype.global` has the value `true` if the `g` flag was used; otherwise, `false`. The `g` flag indicates that the regular expression should be tested against all possible matches in a string. Each call to [`exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) will update its [`lastIndex`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) property, so that the next call to `exec()` will start at the next character.
Some methods, such as [`String.prototype.matchAll()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll) and [`String.prototype.replaceAll()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll), will validate that, if the parameter is a regex, it is global. The regex's [`@@match`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match) and [`@@replace`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace) methods (called by [`String.prototype.match()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) and [`String.prototype.replace()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)) would also have different behaviors when the regex is global.
The set accessor of `global` is `undefined`. You cannot change this property directly.
## Examples
### Using global
```js
const regex = /foo/g;
console.log(regex.global); // true
const str = "fooexamplefoo";
const str1 = str.replace(regex, "");
console.log(str1); // example
const regex1 = /foo/;
const str2 = str.replace(regex1, "");
console.log(str2); // examplefoo
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("RegExp.prototype.lastIndex")}}
- {{jsxref("RegExp.prototype.dotAll")}}
- {{jsxref("RegExp.prototype.hasIndices")}}
- {{jsxref("RegExp.prototype.ignoreCase")}}
- {{jsxref("RegExp.prototype.multiline")}}
- {{jsxref("RegExp.prototype.source")}}
- {{jsxref("RegExp.prototype.sticky")}}
- {{jsxref("RegExp.prototype.unicode")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/compile/index.md | ---
title: RegExp.prototype.compile()
slug: Web/JavaScript/Reference/Global_Objects/RegExp/compile
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.RegExp.compile
---
{{JSRef}} {{Deprecated_Header}}
> **Note:** The `compile()` method is only specified for compatibility reasons. Using `compile()` causes the otherwise immutable regex source and flags to become mutable, which may break user expectations. You can use the [`RegExp()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) constructor to construct a new regular expression object instead.
The **`compile()`** method of {{jsxref("RegExp")}} instances is used to recompile a regular expression with new source and flags after the `RegExp` object has already been created.
## Syntax
```js-nolint
compile(pattern, flags)
```
### Parameters
- `pattern`
- : The text of the regular expression.
- `flags`
- : Any combination of [flag values](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp#flags).
### Return value
None ({{jsxref("undefined")}}).
## Examples
### Using compile()
The following example shows how to recompile a regular expression with a new pattern and a new flag.
```js
const regexObj = new RegExp("foo", "gi");
regexObj.compile("new foo", "g");
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("RegExp")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/unicodesets/index.md | ---
title: RegExp.prototype.unicodeSets
slug: Web/JavaScript/Reference/Global_Objects/RegExp/unicodeSets
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.RegExp.unicodeSets
---
{{JSRef}}
The **`unicodeSets`** accessor property of {{jsxref("RegExp")}} instances returns whether or not the `v` flag is used with this regular expression.
## Description
`RegExp.prototype.unicodeSets` has the value `true` if the `v` flag was used; otherwise, `false`. The `v` flag is an "upgrade" to the [`u`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) flag that enables more Unicode-related features. ("v" is the next letter after "u" in the alphabet.) Because `u` and `v` interpret the same regex in incompatible ways, using both flags results in a {{jsxref("SyntaxError")}}. With the `v` flag, you get all features mentioned in the `u` flag description, plus:
- The [`\p`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape) escape sequence can be additionally used to match properties of strings, instead of just characters.
- The [character class](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class) syntax is upgraded to allow intersection, union, and subtraction syntaxes, as well as matching multiple Unicode characters.
- The character class complement syntax `[^...]` constructs a complement class instead of negating the match result, avoiding some confusing behaviors with case-insensitive matching. For more information, see [Complement classes and case-insensitive matching](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class#complement_classes_and_case-insensitive_matching).
Some valid `u`-mode regexes become invalid in `v`-mode. Specifically, the character class syntax is different and some characters can no longer appear literally. For more information, see [`v`-mode character class](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class#v-mode_character_class).
> **Note:** The `v` mode does not interpret grapheme clusters as single characters; they are still multiple code points. For example, `/[🇺🇳]/v` is still able to match `"🇺"`.
The set accessor of `unicodeSets` is `undefined`. You cannot change this property directly.
## Examples
### Using the unicodeSets property
```js
const regex = /[\p{Script_Extensions=Greek}&&\p{Letter}]/v;
console.log(regex.unicodeSets); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("RegExp.prototype.lastIndex")}}
- {{jsxref("RegExp.prototype.dotAll")}}
- {{jsxref("RegExp.prototype.global")}}
- {{jsxref("RegExp.prototype.hasIndices")}}
- {{jsxref("RegExp.prototype.ignoreCase")}}
- {{jsxref("RegExp.prototype.multiline")}}
- {{jsxref("RegExp.prototype.source")}}
- {{jsxref("RegExp.prototype.sticky")}}
- {{jsxref("RegExp.prototype.unicode")}}
- [RegExp v flag with set notation and properties of strings](https://v8.dev/features/regexp-v-flag) on v8.dev (2022)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/@@split/index.md | ---
title: RegExp.prototype[@@split]()
slug: Web/JavaScript/Reference/Global_Objects/RegExp/@@split
page-type: javascript-instance-method
browser-compat: javascript.builtins.RegExp.@@split
---
{{JSRef}}
The **`[@@split]()`** method of {{jsxref("RegExp")}} instances specifies how [`String.prototype.split`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) should behave when the regular expression is passed in as the separator.
{{EmbedInteractiveExample("pages/js/regexp-prototype-@@split.html")}}
## Syntax
```js-nolint
regexp[Symbol.split](str)
regexp[Symbol.split](str, limit)
```
### Parameters
- `str`
- : The target of the split operation.
- `limit` {{optional_inline}}
- : Integer specifying a limit on the number of splits to be found. The `[@@split]()` method still splits on every match of `this` RegExp pattern (or, in the Syntax above, `regexp`), until the number of split items match the `limit` or the string falls short of `this` pattern.
### Return value
An {{jsxref("Array")}} containing substrings as its elements. Capturing groups are included.
## Description
This method is called internally in {{jsxref("String.prototype.split()")}} when a `RegExp` is passed as the separator. For example, the following two examples return the same result.
```js
"a-b-c".split(/-/);
/-/[Symbol.split]("a-b-c");
```
This method exists for customizing the behavior of `split()` in `RegExp` subclasses.
The `RegExp.prototype[@@split]()` base method exhibits the following behaviors:
- It starts by using [`@@species`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@species) to construct a new regexp, thus avoiding mutating the original regexp in any way.
- The regexp's `g` ("global") flag is ignored, and the `y` ("sticky") flag is always applied even when it was not originally present.
- If the target string is empty, and the regexp can match empty strings (for example, `/a?/`), an empty array is returned. Otherwise, if the regexp can't match an empty string, `[""]` is returned.
- The matching proceeds by continuously calling `this.exec()`. Since the regexp is always sticky, this will move along the string, each time yielding a matching string, index, and any capturing groups.
- For each match, the substring between the last matched string's end and the current matched string's beginning is first appended to the result array. Then, the capturing groups' values are appended one-by-one.
- If the current match is an empty string, or if the regexp doesn't match at the current position (since it's sticky), the `lastIndex` would still be advanced — if the regex is [Unicode-aware](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), it would advance by one Unicode code point; otherwise, it advances by one UTF-16 code unit.
- If the regexp doesn't match the target string, the target string is returned as-is, wrapped in an array.
- The returned array's length will never exceed the `limit` parameter, if provided, while trying to be as close as possible. Therefore, the last match and its capturing groups may not all be present in the returned array if the array is already filled.
## Examples
### Direct call
This method can be used in almost the same way as
{{jsxref("String.prototype.split()")}}, except the different `this` and the
different order of arguments.
```js
const re = /-/g;
const str = "2016-01-02";
const result = re[Symbol.split](str);
console.log(result); // ["2016", "01", "02"]
```
### Using @@split in subclasses
Subclasses of {{jsxref("RegExp")}} can override the `[@@split]()` method to
modify the default behavior.
```js
class MyRegExp extends RegExp {
[Symbol.split](str, limit) {
const result = RegExp.prototype[Symbol.split].call(this, str, limit);
return result.map((x) => `(${x})`);
}
}
const re = new MyRegExp("-");
const str = "2016-01-02";
const result = str.split(re); // String.prototype.split calls re[@@split].
console.log(result); // ["(2016)", "(01)", "(02)"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `RegExp.prototype[@@split]` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.split()")}}
- [`RegExp.prototype[@@match]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match)
- [`RegExp.prototype[@@matchAll]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll)
- [`RegExp.prototype[@@replace]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace)
- [`RegExp.prototype[@@search]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search)
- {{jsxref("RegExp.prototype.exec()")}}
- {{jsxref("RegExp.prototype.test()")}}
- {{jsxref("Symbol.split")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/@@search/index.md | ---
title: RegExp.prototype[@@search]()
slug: Web/JavaScript/Reference/Global_Objects/RegExp/@@search
page-type: javascript-instance-method
browser-compat: javascript.builtins.RegExp.@@search
---
{{JSRef}}
The **`[@@search]()`** method of {{jsxref("RegExp")}} instances specifies how [`String.prototype.search`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search) should behave.
{{EmbedInteractiveExample("pages/js/regexp-prototype-@@search.html")}}
## Syntax
```js-nolint
regexp[Symbol.search](str)
```
### Parameters
- `str`
- : A {{jsxref("String")}} that is a target of the search.
### Return value
The index of the first match between the regular expression and the given string, or `-1` if no match was found.
## Description
This method is called internally in {{jsxref("String.prototype.search()")}}. For example, the following two examples return the same result.
```js
"abc".search(/a/);
/a/[Symbol.search]("abc");
```
This method does not copy the regular expression, unlike [`@@split`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@split) or [`@@matchAll`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll). However, unlike [`@@match`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match) or [`@@replace`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace), it will set [`lastIndex`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) to 0 when execution starts and restore it to the previous value when it exits, therefore generally avoiding side effects. This means that the `g` flag has no effect with this method, and it always returns the first match in the string even when `lastIndex` is non-zero. This also means sticky regexps will always search strictly at the beginning of the string.
```js
const re = /[abc]/g;
re.lastIndex = 2;
console.log("abc".search(re)); // 0
const re2 = /[bc]/y;
re2.lastIndex = 1;
console.log("abc".search(re2)); // -1
console.log("abc".match(re2)); // [ 'b' ]
```
`@@search` always calls the regex's [`exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) method exactly once, and returns the `index` property of the result, or `-1` if the result is `null`.
This method exists for customizing the search behavior in `RegExp` subclasses.
## Examples
### Direct call
This method can be used in almost the same way as {{jsxref("String.prototype.search()")}}, except for the different value of `this` and the different arguments order.
```js
const re = /-/g;
const str = "2016-01-02";
const result = re[Symbol.search](str);
console.log(result); // 4
```
### Using @@search in subclasses
Subclasses of {{jsxref("RegExp")}} can override `[@@search]()` method to modify the behavior.
```js
class MyRegExp extends RegExp {
constructor(str) {
super(str);
this.pattern = str;
}
[Symbol.search](str) {
return str.indexOf(this.pattern);
}
}
const re = new MyRegExp("a+b");
const str = "ab a+b";
const result = str.search(re); // String.prototype.search calls re[@@search].
console.log(result); // 3
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `RegExp.prototype[@@search]` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.search()")}}
- [`RegExp.prototype[@@match]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match)
- [`RegExp.prototype[@@matchAll]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll)
- [`RegExp.prototype[@@replace]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace)
- [`RegExp.prototype[@@split]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@split)
- {{jsxref("RegExp.prototype.exec()")}}
- {{jsxref("RegExp.prototype.test()")}}
- {{jsxref("Symbol.search")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/@@species/index.md | ---
title: RegExp[@@species]
slug: Web/JavaScript/Reference/Global_Objects/RegExp/@@species
page-type: javascript-static-accessor-property
browser-compat: javascript.builtins.RegExp.@@species
---
{{JSRef}}
The **`RegExp[@@species]`** static accessor property returns the constructor used to construct copied regular expressions in certain `RegExp` 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](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible.
{{EmbedInteractiveExample("pages/js/regexp-getregexp-@@species.html")}}
## Syntax
```js-nolint
RegExp[Symbol.species]
```
### Return value
The value of the constructor (`this`) on which `get @@species` was called. The return value is used to construct copied `RegExp` instances.
## Description
The `@@species` accessor property returns the default constructor for `RegExp` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:
```js
// Hypothetical underlying implementation for illustration
class RegExp {
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 SubRegExp extends SubRegExp {}
SubRegExp[Symbol.species] === SubRegExp; // true
```
Some `RegExp` methods create a copy of the current regex instance before running {{jsxref("RegExp/exec", "exec()")}}, so that side effects such as changes to {{jsxref("RegExp/lastIndex", "lastIndex")}} are not retained. The `@@species` property is used to determine the constructor of the new instance. The methods that copy the current regex instance are:
- [`[@@matchAll]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll)
- [`[@@split]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@split)
## Examples
### Species in ordinary objects
The `@@species` property returns the default constructor function, which is the `RegExp` constructor for `RegExp` objects:
```js
RegExp[Symbol.species]; // function RegExp()
```
### Species in derived objects
In an instance of a custom `RegExp` subclass, such as `MyRegExp`, the `MyRegExp` species is the `MyRegExp` constructor. However, you might want to overwrite this, in order to return parent `RegExp` objects in your derived class methods:
```js
class MyRegExp extends RegExp {
// Overwrite MyRegExp species to the parent RegExp constructor
static get [Symbol.species]() {
return RegExp;
}
}
```
Or you can use this to observe the copying process:
```js
class MyRegExp extends RegExp {
constructor(...args) {
console.log("Creating a new MyRegExp instance with args:", args);
super(...args);
}
static get [Symbol.species]() {
console.log("Copying MyRegExp");
return this;
}
exec(value) {
console.log("Executing with lastIndex:", this.lastIndex);
return super.exec(value);
}
}
Array.from("aabbccdd".matchAll(new MyRegExp("[ac]", "g")));
// Creating a new MyRegExp instance with args: [ '[ac]', 'g' ]
// Copying MyRegExp
// Creating a new MyRegExp instance with args: [ MyRegExp /[ac]/g, 'g' ]
// Executing with lastIndex: 0
// Executing with lastIndex: 1
// Executing with lastIndex: 2
// Executing with lastIndex: 5
// Executing with lastIndex: 6
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("RegExp")}}
- {{jsxref("Symbol.species")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp | data/mdn-content/files/en-us/web/javascript/reference/global_objects/regexp/rightcontext/index.md | ---
title: RegExp.rightContext ($')
slug: Web/JavaScript/Reference/Global_Objects/RegExp/rightContext
page-type: javascript-static-accessor-property
status:
- deprecated
browser-compat: javascript.builtins.RegExp.rightContext
---
{{JSRef}} {{Deprecated_Header}}
> **Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See [deprecated RegExp features](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp) for more information.
The **`RegExp.rightContext`** static accessor property returns the substring following the most recent match. `RegExp["$'"]` is an alias for this property.
## Description
Because `rightContext` is a static property of {{jsxref("RegExp")}}, you always use it as `RegExp.rightContext` or `RegExp["$'"]`, rather than as a property of a `RegExp` object you created.
The value of `rightContext` updates whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, `rightContext` is an empty string. The set accessor of `rightContext` is `undefined`, so you cannot change this property directly.
You cannot use the shorthand alias with the dot property accessor (`RegExp.$'`), because `'` is not a valid identifier part, so this causes a {{jsxref("SyntaxError")}}. Use the [bracket notation](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) instead.
`$'` can also be used in the replacement string of {{jsxref("String.prototype.replace()")}}, but that's unrelated to the `RegExp["$'"]` legacy property.
## Examples
### Using rightContext and $'
```js
const re = /hello/g;
re.test("hello world!");
RegExp.rightContext; // " world!"
RegExp["$'"]; // " world!"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("RegExp/input", "RegExp.input ($_)")}}
- {{jsxref("RegExp/lastMatch", "RegExp.lastMatch ($&)")}}
- {{jsxref("RegExp/lastParen", "RegExp.lastParen ($+)")}}
- {{jsxref("RegExp/leftContext", "RegExp.leftContext ($`)")}}
- {{jsxref("RegExp/n", "RegExp.$1, …, RegExp.$9")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/escape/index.md | ---
title: escape()
slug: Web/JavaScript/Reference/Global_Objects/escape
page-type: javascript-function
status:
- deprecated
browser-compat: javascript.builtins.escape
---
{{jsSidebar("Objects")}}{{Deprecated_Header}}
> **Note:** `escape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use {{jsxref("encodeURIComponent()")}} or {{jsxref("encodeURI()")}} if possible.
The **`escape()`** function computes a new string in which certain characters have been replaced by hexadecimal escape sequences.
## Syntax
```js-nolint
escape(str)
```
### Parameters
- `str`
- : A string to be encoded.
### Return value
A new string in which certain characters have been escaped.
## Description
`escape()` is a function property of the global object.
The `escape()` function replaces all characters with escape sequences, with the exception of {{Glossary("ASCII")}} word characters (A–Z, a–z, 0–9, \_) and `@\*_+-./`. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number in the format `%XX`, left-padded with 0 if necessary. Otherwise, it is represented by a four-digit hexadecimal number in the format `%uXXXX`, left-padded with 0 if necessary.
> **Note:** This function was used mostly for [URL encoding](https://en.wikipedia.org/wiki/URL_encoding) and is partly based on the escape format in {{rfc(1738)}}. The escape format is _not_ an [escape sequence](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#escape_sequences) in string literals. You can replace `%XX` with `\xXX` and `%uXXXX` with `\uXXXX` to get a string containing actual string-literal escape sequences.
## Examples
### Using escape()
```js
escape("abc123"); // "abc123"
escape("äöü"); // "%E4%F6%FC"
escape("ć"); // "%u0107"
// special characters
escape("@*_+-./"); // "@*_+-./"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `escape` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("encodeURI")}}
- {{jsxref("encodeURIComponent")}}
- {{jsxref("unescape")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/globalthis/index.md | ---
title: globalThis
slug: Web/JavaScript/Reference/Global_Objects/globalThis
page-type: javascript-global-property
browser-compat: javascript.builtins.globalThis
---
{{jsSidebar("Objects")}}
The **`globalThis`** global property contains the [global `this`](/en-US/docs/Web/JavaScript/Reference/Operators/this#global_context) value, which is usually akin to the [global object](/en-US/docs/Glossary/Global_object).
{{EmbedInteractiveExample("pages/js/globalprops-globalthis.html", "shorter")}}
## Value
The global `this` object.
{{js_property_attributes(1, 0, 1)}}
> **Note:** The `globalThis` property is configurable and writable so that code authors can hide it when executing untrusted code and prevent exposing the global object.
## Description
Historically, accessing the global object has required different syntax in different JavaScript environments. On the web you can use {{domxref("Window/window", "window")}}, {{domxref("Window/self", "self")}}, or {{domxref("Window/frames", "frames")}} - but in [Web Workers](/en-US/docs/Web/API/Worker) only `self` will work. In Node.js none of these work, and you must instead use `global`. The `this` keyword could be used inside functions running in non–strict mode, but `this` will be `undefined` in modules and inside functions running in strict mode. You can also use `Function('return this')()`, but environments that disable {{jsxref("Global_Objects/eval", "eval()")}}, like {{Glossary("CSP")}} in browsers, prevent use of {{jsxref("Function")}} in this way.
The `globalThis` property provides a standard way of accessing the global `this` value (and hence the global object itself) across environments. Unlike similar properties such as `window` and `self`, it's guaranteed to work in window and non-window contexts. In this way, you can access the global object in a consistent manner without having to know which environment the code is being run in. To help you remember the name, just remember that in global scope the `this` value is `globalThis`.
> **Note:** `globalThis` is generally the same concept as the global object (i.e. adding properties to `globalThis` makes them global variables) — this is the case for browsers and Node — but hosts are allowed to provide a different value for `globalThis` that's unrelated to the global object.
### HTML and the WindowProxy
In many engines `globalThis` will be a reference to the actual global object, but in web browsers, due to iframe and cross-window security considerations, it references a {{jsxref("Proxy")}} around the actual global object (which you can't directly access). This distinction is rarely relevant in common usage, but important to be aware of.
### Naming
Several other popular name choices such as `self` and `global` were removed from consideration because of their potential to break compatibility with existing code. See the [language proposal's "naming" document](https://github.com/tc39/proposal-global/blob/master/NAMING.md) for more details.
`globalThis` is, quite literally, the global `this` value. It's the same value as the `this` value in a non-strict function called without an object. It's also the value of `this` in the global scope of a script.
## Examples
### Search for the global across environments
Usually, the global object does not need to be explicitly specified — its properties are automatically accessible as global variables.
```js
console.log(window.Math === Math); // true
```
However, one case where one needs to explicitly access the global object is when _writing_ to it, usually for the purpose of [polyfills](/en-US/docs/Glossary/Polyfill).
Prior to `globalThis`, the only reliable cross-platform way to get the global object for an environment was `Function('return this')()`. However, this causes [CSP](/en-US/docs/Web/HTTP/CSP) violations in some settings, so authors would use a piecewise definition like this (slightly adapted from the [original core-js source](https://github.com/zloirock/core-js/blob/master/packages/core-js/internals/global.js)):
```js
function check(it) {
// Math is known to exist as a global in every environment.
return it && it.Math === Math && it;
}
const globalObject =
check(typeof window === "object" && window) ||
check(typeof self === "object" && self) ||
check(typeof global === "object" && global) ||
// This returns undefined when running in strict mode
(function () {
return this;
})() ||
Function("return this")();
```
After obtaining the global object, we can define new globals on it. For example, adding an implementation for [`Intl`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl):
```js
if (typeof globalObject.Intl === "undefined") {
// No Intl in this environment; define our own on the global scope
Object.defineProperty(globalObject, "Intl", {
value: {
// Our Intl implementation
},
enumerable: false,
configurable: true,
writable: true,
});
}
```
With `globalThis` available, the additional search for the global across environments is not necessary anymore:
```js
if (typeof globalThis.Intl === "undefined") {
Object.defineProperty(globalThis, "Intl", {
value: {
// Our Intl implementation
},
enumerable: false,
configurable: true,
writable: true,
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `globalThis` in `core-js`](https://github.com/zloirock/core-js#ecmascript-globalthis)
- {{jsxref("Operators/this", "this")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/bigint64array/index.md | ---
title: BigInt64Array
slug: Web/JavaScript/Reference/Global_Objects/BigInt64Array
page-type: javascript-class
browser-compat: javascript.builtins.BigInt64Array
---
{{JSRef}}
The **`BigInt64Array`** typed array represents an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use {{jsxref("DataView")}} instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
`BigInt64Array` is a subclass of the hidden {{jsxref("TypedArray")}} class.
{{EmbedInteractiveExample("pages/js/typedarray-bigint64.html", "taller")}}
## Constructor
- {{jsxref("BigInt64Array/BigInt64Array", "BigInt64Array()")}}
- : Creates a new `BigInt64Array` object.
## Static properties
_Also inherits static properties from its parent {{jsxref("TypedArray")}}_.
- {{jsxref("TypedArray/BYTES_PER_ELEMENT", "BigInt64Array.BYTES_PER_ELEMENT")}}
- : Returns a number value of the element size. `8` in the case of `BigInt64Array`.
## Static methods
_Inherits static methods from its parent {{jsxref("TypedArray")}}_.
## Instance properties
_Also inherits instance properties from its parent {{jsxref("TypedArray")}}_.
These properties are defined on `BigInt64Array.prototype` and shared by all `BigInt64Array` instances.
- {{jsxref("TypedArray/BYTES_PER_ELEMENT", "BigInt64Array.prototype.BYTES_PER_ELEMENT")}}
- : Returns a number value of the element size. `8` in the case of a `BigInt64Array`.
- {{jsxref("Object/constructor", "BigInt64Array.prototype.constructor")}}
- : The constructor function that created the instance object. For `BigInt64Array` instances, the initial value is the {{jsxref("BigInt64Array/BigInt64Array", "BigInt64Array")}} constructor.
## Instance methods
_Inherits instance methods from its parent {{jsxref("TypedArray")}}_.
## Examples
### Different ways to create a BigInt64Array
```js
// From a length
const bigint64 = new BigInt64Array(2);
bigint64[0] = 42n;
console.log(bigint64[0]); // 42n
console.log(bigint64.length); // 2
console.log(bigint64.BYTES_PER_ELEMENT); // 8
// From an array
const x = new BigInt64Array([21n, 31n]);
console.log(x[1]); // 31n
// From another TypedArray
const y = new BigInt64Array(x);
console.log(y[0]); // 21n
// From an ArrayBuffer
const buffer = new ArrayBuffer(64);
const z = new BigInt64Array(buffer, 8, 4);
console.log(z.byteOffset); // 8
// From an iterable
const iterable = (function* () {
yield* [1n, 2n, 3n];
})();
const bigint64FromIterable = new BigInt64Array(iterable);
console.log(bigint64FromIterable);
// BigInt64Array [1n, 2n, 3n]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("TypedArray")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("DataView")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/bigint64array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/bigint64array/bigint64array/index.md | ---
title: BigInt64Array() constructor
slug: Web/JavaScript/Reference/Global_Objects/BigInt64Array/BigInt64Array
page-type: javascript-constructor
browser-compat: javascript.builtins.BigInt64Array.BigInt64Array
---
{{JSRef}}
The **`BigInt64Array()`** constructor creates {{jsxref("BigInt64Array")}} objects. The contents are initialized to `0n`.
## Syntax
```js-nolint
new BigInt64Array()
new BigInt64Array(length)
new BigInt64Array(typedArray)
new BigInt64Array(object)
new BigInt64Array(buffer)
new BigInt64Array(buffer, byteOffset)
new BigInt64Array(buffer, byteOffset, length)
```
> **Note:** `BigInt64Array()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters).
### Exceptions
See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions).
## Examples
### Different ways to create a BigInt64Array
```js
// From a length
const bigint64 = new BigInt64Array(2);
bigint64[0] = 42n;
console.log(bigint64[0]); // 42n
console.log(bigint64.length); // 2
console.log(bigint64.BYTES_PER_ELEMENT); // 8
// From an array
const x = new BigInt64Array([21n, 31n]);
console.log(x[1]); // 31n
// From another TypedArray
const y = new BigInt64Array(x);
console.log(y[0]); // 21n
// From an ArrayBuffer
const buffer = new ArrayBuffer(64);
const z = new BigInt64Array(buffer, 8, 4);
console.log(z.byteOffset); // 8
// From an iterable
const iterable = (function* () {
yield* [1n, 2n, 3n];
})();
const bigint64FromIterable = new BigInt64Array(iterable);
console.log(bigint64FromIterable);
// BigInt64Array [1n, 2n, 3n]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("TypedArray")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("DataView")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/index.md | ---
title: Array
slug: Web/JavaScript/Reference/Global_Objects/Array
page-type: javascript-class
browser-compat: javascript.builtins.Array
---
{{JSRef}}
The **`Array`** object, as with arrays in other programming languages, enables [storing a collection of multiple items under a single variable name](/en-US/docs/Learn/JavaScript/First_steps/Arrays), and has members for [performing common array operations](#examples).
## Description
In JavaScript, arrays aren't [primitives](/en-US/docs/Glossary/Primitive) but are instead `Array` objects with the following core characteristics:
- **JavaScript arrays are resizable** and **can contain a mix of different [data types](/en-US/docs/Web/JavaScript/Data_structures)**. (When those characteristics are undesirable, use [typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) instead.)
- **JavaScript arrays are not associative arrays** and so, array elements cannot be accessed using arbitrary strings as indexes, but must be accessed using nonnegative integers (or their respective string form) as indexes.
- **JavaScript arrays are [zero-indexed](https://en.wikipedia.org/wiki/Zero-based_numbering)**: the first element of an array is at index `0`, the second is at index `1`, and so on — and the last element is at the value of the array's {{jsxref("Array/length", "length")}} property minus `1`.
- **JavaScript [array-copy operations](#copy_an_array) create [shallow copies](/en-US/docs/Glossary/Shallow_copy)**. (All standard built-in copy operations with _any_ JavaScript objects create shallow copies, rather than [deep copies](/en-US/docs/Glossary/Deep_copy)).
### Array indices
`Array` objects cannot use arbitrary strings as element indexes (as in an [associative array](https://en.wikipedia.org/wiki/Associative_array)) but must use nonnegative integers (or their respective string form). Setting or accessing via non-integers will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's [object property collection](/en-US/docs/Web/JavaScript/Data_structures#properties). The array's object properties and list of array elements are separate, and the array's [traversal and mutation operations](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#array_methods) cannot be applied to these named properties.
Array elements are object properties in the same way that `toString` is a property (to be specific, however, `toString()` is a method). Nevertheless, trying to access an element of an array as follows throws a syntax error because the property name is not valid:
```js-nolint example-bad
arr.0; // a syntax error
```
JavaScript syntax requires properties beginning with a digit to be accessed using [bracket notation](/en-US/docs/Web/JavaScript/Guide/Working_with_objects#objects_and_properties) instead of [dot notation](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors). It's also possible to quote the array indices (e.g., `years['2']` instead of `years[2]`), although usually not necessary.
The `2` in `years[2]` is coerced into a string by the JavaScript engine through an implicit `toString` conversion. As a result, `'2'` and `'02'` would refer to two different slots on the `years` object, and the following example could be `true`:
```js
console.log(years["2"] !== years["02"]);
```
Only `years['2']` is an actual array index. `years['02']` is an arbitrary string property that will not be visited in array iteration.
### Relationship between length and numerical properties
A JavaScript array's {{jsxref("Array/length", "length")}} property and numerical properties are connected.
Several of the built-in array methods (e.g., {{jsxref("Array/join", "join()")}}, {{jsxref("Array/slice", "slice()")}}, {{jsxref("Array/indexOf", "indexOf()")}}, etc.) take into account the value of an array's {{jsxref("Array/length", "length")}} property when they're called.
Other methods (e.g., {{jsxref("Array/push", "push()")}}, {{jsxref("Array/splice", "splice()")}}, etc.) also result in updates to an array's {{jsxref("Array/length", "length")}} property.
```js
const fruits = [];
fruits.push("banana", "apple", "peach");
console.log(fruits.length); // 3
```
When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's {{jsxref("Array/length", "length")}} property accordingly:
```js
fruits[5] = "mango";
console.log(fruits[5]); // 'mango'
console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
console.log(fruits.length); // 6
```
Increasing the {{jsxref("Array/length", "length")}} extends the array by adding empty slots without creating any new elements — not even `undefined`.
```js
fruits.length = 10;
console.log(fruits); // ['banana', 'apple', 'peach', empty x 2, 'mango', empty x 4]
console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
console.log(fruits.length); // 10
console.log(fruits[8]); // undefined
```
Decreasing the {{jsxref("Array/length", "length")}} property does, however, delete elements.
```js
fruits.length = 2;
console.log(Object.keys(fruits)); // ['0', '1']
console.log(fruits.length); // 2
```
This is explained further on the {{jsxref("Array/length", "length")}} page.
### Array methods and empty slots
Array methods have different behaviors when encountering empty slots in [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays). In general, older methods (e.g. `forEach`) treat empty slots differently from indices that contain `undefined`.
Methods that have special treatment for empty slots include the following: {{jsxref("Array/concat", "concat()")}}, {{jsxref("Array/copyWithin", "copyWithin()")}}, {{jsxref("Array/every", "every()")}}, {{jsxref("Array/filter", "filter()")}}, {{jsxref("Array/flat", "flat()")}}, {{jsxref("Array/flatMap", "flatMap()")}}, {{jsxref("Array/forEach", "forEach()")}}, {{jsxref("Array/indexOf", "indexOf()")}}, {{jsxref("Array/lastIndexOf", "lastIndexOf()")}}, {{jsxref("Array/map", "map()")}}, {{jsxref("Array/reduce", "reduce()")}}, {{jsxref("Array/reduceRight", "reduceRight()")}}, {{jsxref("Array/reverse", "reverse()")}}, {{jsxref("Array/slice", "slice()")}}, {{jsxref("Array/some", "some()")}}, {{jsxref("Array/sort", "sort()")}}, and {{jsxref("Array/splice", "splice()")}}. Iteration methods such as `forEach` don't visit empty slots at all. Other methods, such as `concat`, `copyWithin`, etc., preserve empty slots when doing the copying, so in the end the array is still sparse.
```js
const colors = ["red", "yellow", "blue"];
colors[5] = "purple";
colors.forEach((item, index) => {
console.log(`${index}: ${item}`);
});
// Output:
// 0: red
// 1: yellow
// 2: blue
// 5: purple
colors.reverse(); // ['purple', empty × 2, 'blue', 'yellow', 'red']
```
Newer methods (e.g. `keys`) do not treat empty slots specially and treat them as if they contain `undefined`. Methods that conflate empty slots with `undefined` elements include the following: {{jsxref("Array/entries", "entries()")}}, {{jsxref("Array/fill", "fill()")}}, {{jsxref("Array/find", "find()")}}, {{jsxref("Array/findIndex", "findIndex()")}}, {{jsxref("Array/findLast", "findLast()")}}, {{jsxref("Array/findLastIndex", "findLastIndex()")}}, {{jsxref("Array/includes", "includes()")}}, {{jsxref("Array/join", "join()")}}, {{jsxref("Array/keys", "keys()")}}, {{jsxref("Array/toLocaleString", "toLocaleString()")}}, {{jsxref("Array/toReversed", "toReversed()")}}, {{jsxref("Array/toSorted", "toSorted()")}}, {{jsxref("Array/toSpliced", "toSpliced()")}}, {{jsxref("Array/values", "values()")}}, and {{jsxref("Array/with", "with()")}}.
```js
const colors = ["red", "yellow", "blue"];
colors[5] = "purple";
const iterator = colors.keys();
for (const key of iterator) {
console.log(`${key}: ${colors[key]}`);
}
// Output
// 0: red
// 1: yellow
// 2: blue
// 3: undefined
// 4: undefined
// 5: purple
const newColors = colors.toReversed(); // ['purple', undefined, undefined, 'blue', 'yellow', 'red']
```
### Copying methods and mutating methods
Some methods do not mutate the existing array that the method was called on, but instead return a new array. They do so by first constructing a new array and then populating it with elements. The copy always happens [_shallowly_](/en-US/docs/Glossary/Shallow_copy) — the method never copies anything beyond the initially created array. Elements of the original array(s) are copied into the new array as follows:
- Objects: the object reference is copied into the new array. Both the original and new array refer to the same object. That is, if a referenced object is modified, the changes are visible to both the new and original arrays.
- Primitive types such as strings, numbers and booleans (not {{jsxref("String")}}, {{jsxref("Number")}}, and {{jsxref("Boolean")}} objects): their values are copied into the new array.
Other methods mutate the array that the method was called on, in which case their return value differs depending on the method: sometimes a reference to the same array, sometimes the length of the new array.
The following methods create new arrays by accessing [`this.constructor[Symbol.species]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@species) to determine the constructor to use: {{jsxref("Array/concat", "concat()")}}, {{jsxref("Array/filter", "filter()")}}, {{jsxref("Array/flat", "flat()")}}, {{jsxref("Array/flatMap", "flatMap()")}}, {{jsxref("Array/map", "map()")}}, {{jsxref("Array/slice", "slice()")}}, and {{jsxref("Array/splice", "splice()")}} (to construct the array of removed elements that's returned).
The following methods always create new arrays with the `Array` base constructor: {{jsxref("Array/toReversed", "toReversed()")}}, {{jsxref("Array/toSorted", "toSorted()")}}, {{jsxref("Array/toSpliced", "toSpliced()")}}, and {{jsxref("Array/with", "with()")}}.
The following table lists the methods that mutate the original array, and the corresponding non-mutating alternative:
| Mutating method | Non-mutating alternative |
| ---------------------------------------------- | -------------------------------------------------------- |
| {{jsxref("Array/copyWithin", "copyWithin()")}} | No one-method alternative |
| {{jsxref("Array/fill", "fill()")}} | No one-method alternative |
| {{jsxref("Array/pop", "pop()")}} | {{jsxref("Array/slice", "slice(0, -1)")}} |
| {{jsxref("Array/push", "push(v1, v2)")}} | {{jsxref("Array/concat", "concat([v1, v2])")}} |
| {{jsxref("Array/reverse", "reverse()")}} | {{jsxref("Array/toReversed", "toReversed()")}} |
| {{jsxref("Array/shift", "shift()")}} | {{jsxref("Array/slice", "slice(1)")}} |
| {{jsxref("Array/sort", "sort()")}} | {{jsxref("Array/toSorted", "toSorted()")}} |
| {{jsxref("Array/splice", "splice()")}} | {{jsxref("Array/toSpliced", "toSpliced()")}} |
| {{jsxref("Array/unshift", "unshift(v1, v2)")}} | {{jsxref("Array/toSpliced", "toSpliced(0, 0, v1, v2)")}} |
An easy way to change a mutating method into a non-mutating alternative is to use the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) or {{jsxref("Array/slice", "slice()")}} to create a copy first:
```js-nolint
arr.copyWithin(0, 1, 2); // mutates arr
const arr2 = arr.slice().copyWithin(0, 1, 2); // does not mutate arr
const arr3 = [...arr].copyWithin(0, 1, 2); // does not mutate arr
```
### Iterative methods
Many array methods take a callback function as an argument. The callback function is called sequentially and at most once for each element in the array, and the return value of the callback function is used to determine the return value of the method. They all share the same signature:
```js-nolint
method(callbackFn, thisArg)
```
Where `callbackFn` takes three arguments:
- `element`
- : The current element being processed in the array.
- `index`
- : The index of the current element being processed in the array.
- `array`
- : The array that the method was called upon.
What `callbackFn` is expected to return depends on the array method that was called.
The `thisArg` argument (defaults to `undefined`) will be used as the `this` value when calling `callbackFn`. The `this` value ultimately observable by `callbackFn` is determined according to [the usual rules](/en-US/docs/Web/JavaScript/Reference/Operators/this): if `callbackFn` is [non-strict](/en-US/docs/Web/JavaScript/Reference/Strict_mode#no_this_substitution), primitive `this` values are wrapped into objects, and `undefined`/`null` is substituted with [`globalThis`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis). The `thisArg` argument is irrelevant for any `callbackFn` defined with an [arrow function](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), as arrow functions don't have their own `this` {{Glossary("binding")}}.
The `array` argument passed to `callbackFn` is most useful if you want to read another index during iteration, because you may not always have an existing variable that refers to the current array. You should generally not mutate the array during iteration (see [mutating initial array in iterative methods](#mutating_initial_array_in_iterative_methods)), but you can also use this argument to do so. The `array` argument is _not_ the array that is being built, in the case of methods like `map()`, `filter()`, and `flatMap()` — there is no way to access the array being built from the callback function.
All iterative methods are [copying](#copying_methods_and_mutating_methods) and [generic](#generic_array_methods), although they behave differently with [empty slots](#array_methods_and_empty_slots).
The following methods are iterative:{{jsxref("Array/every", "every()")}}, {{jsxref("Array/filter", "filter()")}}, {{jsxref("Array/find", "find()")}}, {{jsxref("Array/findIndex", "findIndex()")}}, {{jsxref("Array/findLast", "findLast()")}}, {{jsxref("Array/findLastIndex", "findLastIndex()")}}, {{jsxref("Array/flatMap", "flatMap()")}}, {{jsxref("Array/forEach", "forEach()")}}, {{jsxref("Array/map", "map()")}}, and {{jsxref("Array/some", "some()")}}.
In particular, {{jsxref("Array/every", "every()")}}, {{jsxref("Array/find", "find()")}}, {{jsxref("Array/findIndex", "findIndex()")}}, {{jsxref("Array/findLast", "findLast()")}}, {{jsxref("Array/findLastIndex", "findLastIndex()")}}, and {{jsxref("Array/some", "some()")}} do not always invoke `callbackFn` on every element — they stop iteration as soon as the return value is determined.
The {{jsxref("Array/reduce", "reduce()")}} and {{jsxref("Array/reduceRight", "reduceRight()")}} methods also take a callback function and run it at most once for each element in the array, but they have slightly different signatures from typical iterative methods (for example, they don't accept `thisArg`).
The {{jsxref("Array/sort", "sort()")}} method also takes a callback function, but it is not an iterative method. It mutates the array in-place, doesn't accept `thisArg`, and may invoke the callback multiple times on an index.
Iterative methods iterate the array like the following (with a lot of technical details omitted):
```js
function method(callbackFn, thisArg) {
const length = this.length;
for (let i = 0; i < length; i++) {
if (i in this) {
const result = callbackFn.call(thisArg, this[i], i, this);
// Do something with result; maybe return early
}
}
}
```
Note the following:
1. Not all methods do the `i in this` test. The `find`, `findIndex`, `findLast`, and `findLastIndex` methods do not, but other methods do.
2. The `length` is memorized before the loop starts. This affects how insertions and deletions during iteration are handled (see [mutating initial array in iterative methods](#mutating_initial_array_in_iterative_methods)).
3. The method doesn't memorize the array contents, so if any index is modified during iteration, the new value might be observed.
4. The code above iterates the array in ascending order of index. Some methods iterate in descending order of index (`for (let i = length - 1; i >= 0; i--)`): `reduceRight()`, `findLast()`, and `findLastIndex()`.
5. `reduce` and `reduceRight` have slightly different signatures and do not always start at the first/last element.
### Generic array methods
Array methods are always generic — they don't access any internal data of the array object. They only access the array elements through the `length` property and the indexed elements. This means that they can be called on array-like objects as well.
```js
const arrayLike = {
0: "a",
1: "b",
length: 2,
};
console.log(Array.prototype.join.call(arrayLike, "+")); // 'a+b'
```
#### Normalization of the length property
The `length` property is [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) and then clamped to the range between 0 and 2<sup>53</sup> - 1. `NaN` becomes `0`, so even when `length` is not present or is `undefined`, it behaves as if it has value `0`.
The language avoids setting `length` to an [unsafe integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). All built-in methods will throw a {{jsxref("TypeError")}} if `length` will be set to a number greater than 2<sup>53</sup> - 1. However, because the {{jsxref("Array/length", "length")}} property of arrays throws an error if it's set to greater than 2<sup>32</sup> - 1, the safe integer threshold is usually not reached unless the method is called on a non-array object.
```js
Array.prototype.flat.call({}); // []
```
Some array methods set the `length` property of the array object. They always set the value after normalization, so `length` always ends as an integer.
```js
const a = { length: 0.7 };
Array.prototype.push.call(a);
console.log(a.length); // 0
```
#### Array-like objects
The term [_array-like object_](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects) refers to any object that doesn't throw during the `length` conversion process described above. In practice, such object is expected to actually have a `length` property and to have indexed elements in the range `0` to `length - 1`. (If it doesn't have all indices, it will be functionally equivalent to a [sparse array](#array_methods_and_empty_slots).) Any integer index less than zero or greater than `length - 1` is ignored when an array method operates on an array-like object.
Many DOM objects are array-like — for example, [`NodeList`](/en-US/docs/Web/API/NodeList) and [`HTMLCollection`](/en-US/docs/Web/API/HTMLCollection). The [`arguments`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments) object is also array-like. You can call array methods on them even if they don't have these methods themselves.
```js
function f() {
console.log(Array.prototype.join.call(arguments, "+"));
}
f("a", "b"); // 'a+b'
```
## Constructor
- {{jsxref("Array/Array", "Array()")}}
- : Creates a new `Array` object.
## Static properties
- {{jsxref("Array/@@species", "Array[@@species]")}}
- : Returns the `Array` constructor.
## Static methods
- {{jsxref("Array.from()")}}
- : Creates a new `Array` instance from an iterable or array-like object.
- {{jsxref("Array.fromAsync()")}}
- : Creates a new `Array` instance from an async iterable, iterable, or array-like object.
- {{jsxref("Array.isArray()")}}
- : Returns `true` if the argument is an array, or `false` otherwise.
- {{jsxref("Array.of()")}}
- : Creates a new `Array` instance with a variable number of arguments, regardless of number or type of the arguments.
## Instance properties
These properties are defined on `Array.prototype` and shared by all `Array` instances.
- {{jsxref("Object/constructor", "Array.prototype.constructor")}}
- : The constructor function that created the instance object. For `Array` instances, the initial value is the {{jsxref("Array/Array", "Array")}} constructor.
- {{jsxref("Array/@@unscopables", "Array.prototype[@@unscopables]")}}
- : Contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for [`with`](/en-US/docs/Web/JavaScript/Reference/Statements/with) statement-binding purposes.
These properties are own properties of each `Array` instance.
- {{jsxref("Array/length", "length")}}
- : Reflects the number of elements in an array.
## Instance methods
- {{jsxref("Array.prototype.at()")}}
- : Returns the array item at the given index. Accepts negative integers, which count back from the last item.
- {{jsxref("Array.prototype.concat()")}}
- : Returns a new array that is the calling array joined with other array(s) and/or value(s).
- {{jsxref("Array.prototype.copyWithin()")}}
- : Copies a sequence of array elements within an array.
- {{jsxref("Array.prototype.entries()")}}
- : Returns a new [_array iterator_](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) object that contains the key/value pairs for each index in an array.
- {{jsxref("Array.prototype.every()")}}
- : Returns `true` if every element in the calling array satisfies the testing function.
- {{jsxref("Array.prototype.fill()")}}
- : Fills all the elements of an array from a start index to an end index with a static value.
- {{jsxref("Array.prototype.filter()")}}
- : Returns a new array containing all elements of the calling array for which the provided filtering function returns `true`.
- {{jsxref("Array.prototype.find()")}}
- : Returns the value of the first element in the array that satisfies the provided testing function, or `undefined` if no appropriate element is found.
- {{jsxref("Array.prototype.findIndex()")}}
- : Returns the index of the first element in the array that satisfies the provided testing function, or `-1` if no appropriate element was found.
- {{jsxref("Array.prototype.findLast()")}}
- : Returns the value of the last element in the array that satisfies the provided testing function, or `undefined` if no appropriate element is found.
- {{jsxref("Array.prototype.findLastIndex()")}}
- : Returns the index of the last element in the array that satisfies the provided testing function, or `-1` if no appropriate element was found.
- {{jsxref("Array.prototype.flat()")}}
- : Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
- {{jsxref("Array.prototype.flatMap()")}}
- : Returns a new array formed by applying a given callback function to each element of the calling array, and then flattening the result by one level.
- {{jsxref("Array.prototype.forEach()")}}
- : Calls a function for each element in the calling array.
- {{jsxref("Array.prototype.includes()")}}
- : Determines whether the calling array contains a value, returning `true` or `false` as appropriate.
- {{jsxref("Array.prototype.indexOf()")}}
- : Returns the first (least) index at which a given element can be found in the calling array.
- {{jsxref("Array.prototype.join()")}}
- : Joins all elements of an array into a string.
- {{jsxref("Array.prototype.keys()")}}
- : Returns a new [_array iterator_](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) that contains the keys for each index in the calling array.
- {{jsxref("Array.prototype.lastIndexOf()")}}
- : Returns the last (greatest) index at which a given element can be found in the calling array, or `-1` if none is found.
- {{jsxref("Array.prototype.map()")}}
- : Returns a new array containing the results of invoking a function on every element in the calling array.
- {{jsxref("Array.prototype.pop()")}}
- : Removes the last element from an array and returns that element.
- {{jsxref("Array.prototype.push()")}}
- : Adds one or more elements to the end of an array, and returns the new `length` of the array.
- {{jsxref("Array.prototype.reduce()")}}
- : Executes a user-supplied "reducer" callback function on each element of the array (from left to right), to reduce it to a single value.
- {{jsxref("Array.prototype.reduceRight()")}}
- : Executes a user-supplied "reducer" callback function on each element of the array (from right to left), to reduce it to a single value.
- {{jsxref("Array.prototype.reverse()")}}
- : Reverses the order of the elements of an array _in place_. (First becomes the last, last becomes first.)
- {{jsxref("Array.prototype.shift()")}}
- : Removes the first element from an array and returns that element.
- {{jsxref("Array.prototype.slice()")}}
- : Extracts a section of the calling array and returns a new array.
- {{jsxref("Array.prototype.some()")}}
- : Returns `true` if at least one element in the calling array satisfies the provided testing function.
- {{jsxref("Array.prototype.sort()")}}
- : Sorts the elements of an array in place and returns the array.
- {{jsxref("Array.prototype.splice()")}}
- : Adds and/or removes elements from an array.
- {{jsxref("Array.prototype.toLocaleString()")}}
- : Returns a localized string representing the calling array and its elements. Overrides the {{jsxref("Object.prototype.toLocaleString()")}} method.
- {{jsxref("Array.prototype.toReversed()")}}
- : Returns a new array with the elements in reversed order, without modifying the original array.
- {{jsxref("Array.prototype.toSorted()")}}
- : Returns a new array with the elements sorted in ascending order, without modifying the original array.
- {{jsxref("Array.prototype.toSpliced()")}}
- : Returns a new array with some elements removed and/or replaced at a given index, without modifying the original array.
- {{jsxref("Array.prototype.toString()")}}
- : Returns a string representing the calling array and its elements. Overrides the {{jsxref("Object.prototype.toString()")}} method.
- {{jsxref("Array.prototype.unshift()")}}
- : Adds one or more elements to the front of an array, and returns the new `length` of the array.
- {{jsxref("Array.prototype.values()")}}
- : Returns a new [_array iterator_](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) object that contains the values for each index in the array.
- {{jsxref("Array.prototype.with()")}}
- : Returns a new array with the element at the given index replaced with the given value, without modifying the original array.
- [`Array.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator)
- : An alias for the [`values()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/values) method by default.
## Examples
This section provides some examples of common array operations in JavaScript.
> **Note:** If you're not yet familiar with array basics, consider first reading [JavaScript First Steps: Arrays](/en-US/docs/Learn/JavaScript/First_steps/Arrays), which [explains what arrays are](/en-US/docs/Learn/JavaScript/First_steps/Arrays#what_is_an_array), and includes other examples of common array operations.
### Create an array
This example shows three ways to create new array: first using [array literal notation](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array#array_literal_notation), then using the [`Array()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array) constructor, and finally using [`String.prototype.split()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) to build the array from a string.
```js
// 'fruits' array created using array literal notation.
const fruits = ["Apple", "Banana"];
console.log(fruits.length);
// 2
// 'fruits2' array created using the Array() constructor.
const fruits2 = new Array("Apple", "Banana");
console.log(fruits2.length);
// 2
// 'fruits3' array created using String.prototype.split().
const fruits3 = "Apple, Banana".split(", ");
console.log(fruits3.length);
// 2
```
### Create a string from an array
This example uses the [`join()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) method to create a string from the `fruits` array.
```js
const fruits = ["Apple", "Banana"];
const fruitsString = fruits.join(", ");
console.log(fruitsString);
// "Apple, Banana"
```
### Access an array item by its index
This example shows how to access items in the `fruits` array by specifying the index number of their position in the array.
```js
const fruits = ["Apple", "Banana"];
// The index of an array's first element is always 0.
fruits[0]; // Apple
// The index of an array's second element is always 1.
fruits[1]; // Banana
// The index of an array's last element is always one
// less than the length of the array.
fruits[fruits.length - 1]; // Banana
// Using an index number larger than the array's length
// returns 'undefined'.
fruits[99]; // undefined
```
### Find the index of an item in an array
This example uses the [`indexOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) method to find the position (index) of the string `"Banana"` in the `fruits` array.
```js
const fruits = ["Apple", "Banana"];
console.log(fruits.indexOf("Banana"));
// 1
```
### Check if an array contains a certain item
This example shows two ways to check if the `fruits` array contains `"Banana"` and `"Cherry"`: first with the [`includes()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) method, and then with the [`indexOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) method to test for an index value that's not `-1`.
```js
const fruits = ["Apple", "Banana"];
fruits.includes("Banana"); // true
fruits.includes("Cherry"); // false
// If indexOf() doesn't return -1, the array contains the given item.
fruits.indexOf("Banana") !== -1; // true
fruits.indexOf("Cherry") !== -1; // false
```
### Append an item to an array
This example uses the [`push()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) method to append a new string to the `fruits` array.
```js
const fruits = ["Apple", "Banana"];
const newLength = fruits.push("Orange");
console.log(fruits);
// ["Apple", "Banana", "Orange"]
console.log(newLength);
// 3
```
### Remove the last item from an array
This example uses the [`pop()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) method to remove the last item from the `fruits` array.
```js
const fruits = ["Apple", "Banana", "Orange"];
const removedItem = fruits.pop();
console.log(fruits);
// ["Apple", "Banana"]
console.log(removedItem);
// Orange
```
> **Note:** `pop()` can only be used to remove the last item from an array. To remove multiple items from the end of an array, see the next example.
### Remove multiple items from the end of an array
This example uses the [`splice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) method to remove the last 3 items from the `fruits` array.
```js
const fruits = ["Apple", "Banana", "Strawberry", "Mango", "Cherry"];
const start = -3;
const removedItems = fruits.splice(start);
console.log(fruits);
// ["Apple", "Banana"]
console.log(removedItems);
// ["Strawberry", "Mango", "Cherry"]
```
### Truncate an array down to just its first N items
This example uses the [`splice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) method to truncate the `fruits` array down to just its first 2 items.
```js
const fruits = ["Apple", "Banana", "Strawberry", "Mango", "Cherry"];
const start = 2;
const removedItems = fruits.splice(start);
console.log(fruits);
// ["Apple", "Banana"]
console.log(removedItems);
// ["Strawberry", "Mango", "Cherry"]
```
### Remove the first item from an array
This example uses the [`shift()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) method to remove the first item from the `fruits` array.
```js
const fruits = ["Apple", "Banana"];
const removedItem = fruits.shift();
console.log(fruits);
// ["Banana"]
console.log(removedItem);
// Apple
```
> **Note:** `shift()` can only be used to remove the first item from an array. To remove multiple items from the beginning of an array, see the next example.
### Remove multiple items from the beginning of an array
This example uses the [`splice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) method to remove the first 3 items from the `fruits` array.
```js
const fruits = ["Apple", "Strawberry", "Cherry", "Banana", "Mango"];
const start = 0;
const deleteCount = 3;
const removedItems = fruits.splice(start, deleteCount);
console.log(fruits);
// ["Banana", "Mango"]
console.log(removedItems);
// ["Apple", "Strawberry", "Cherry"]
```
### Add a new first item to an array
This example uses the [`unshift()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) method to add, at index `0`, a new item to the `fruits` array — making it the new first item in the array.
```js
const fruits = ["Banana", "Mango"];
const newLength = fruits.unshift("Strawberry");
console.log(fruits);
// ["Strawberry", "Banana", "Mango"]
console.log(newLength);
// 3
```
### Remove a single item by index
This example uses the [`splice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) method to remove the string `"Banana"` from the `fruits` array — by specifying the index position of `"Banana"`.
```js
const fruits = ["Strawberry", "Banana", "Mango"];
const start = fruits.indexOf("Banana");
const deleteCount = 1;
const removedItems = fruits.splice(start, deleteCount);
console.log(fruits);
// ["Strawberry", "Mango"]
console.log(removedItems);
// ["Banana"]
```
### Remove multiple items by index
This example uses the [`splice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) method to remove the strings `"Banana"` and `"Strawberry"` from the `fruits` array — by specifying the index position of `"Banana"`, along with a count of the number of total items to remove.
```js
const fruits = ["Apple", "Banana", "Strawberry", "Mango"];
const start = 1;
const deleteCount = 2;
const removedItems = fruits.splice(start, deleteCount);
console.log(fruits);
// ["Apple", "Mango"]
console.log(removedItems);
// ["Banana", "Strawberry"]
```
### Replace multiple items in an array
This example uses the [`splice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) method to replace the last 2 items in the `fruits` array with new items.
```js
const fruits = ["Apple", "Banana", "Strawberry"];
const start = -2;
const deleteCount = 2;
const removedItems = fruits.splice(start, deleteCount, "Mango", "Cherry");
console.log(fruits);
// ["Apple", "Mango", "Cherry"]
console.log(removedItems);
// ["Banana", "Strawberry"]
```
### Iterate over an array
This example uses a [`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop to iterate over the `fruits` array, logging each item to the console.
```js
const fruits = ["Apple", "Mango", "Cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
// Apple
// Mango
// Cherry
```
But `for...of` is just one of many ways to iterate over any array; for more ways, see [Loops and iteration](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration), and see the documentation for the [`every()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every), [`filter()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), [`flatMap()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap), [`map()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), [`reduce()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce), and [`reduceRight()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) methods — and see the next example, which uses the [`forEach()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) method.
### Call a function on each element in an array
This example uses the [`forEach()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) method to call a function on each element in the `fruits` array; the function causes each item to be logged to the console, along with the item's index number.
```js
const fruits = ["Apple", "Mango", "Cherry"];
fruits.forEach((item, index, array) => {
console.log(item, index);
});
// Apple 0
// Mango 1
// Cherry 2
```
### Merge multiple arrays together
This example uses the [`concat()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) method to merge the `fruits` array with a `moreFruits` array, to produce a new `combinedFruits` array. Notice that `fruits` and `moreFruits` remain unchanged.
```js
const fruits = ["Apple", "Banana", "Strawberry"];
const moreFruits = ["Mango", "Cherry"];
const combinedFruits = fruits.concat(moreFruits);
console.log(combinedFruits);
// ["Apple", "Banana", "Strawberry", "Mango", "Cherry"]
// The 'fruits' array remains unchanged.
console.log(fruits);
// ["Apple", "Banana", "Strawberry"]
// The 'moreFruits' array also remains unchanged.
console.log(moreFruits);
// ["Mango", "Cherry"]
```
### Copy an array
This example shows three ways to create a new array from the existing `fruits` array: first by using [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax), then by using the [`from()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) method, and then by using the [`slice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) method.
```js
const fruits = ["Strawberry", "Mango"];
// Create a copy using spread syntax.
const fruitsCopy = [...fruits];
// ["Strawberry", "Mango"]
// Create a copy using the from() method.
const fruitsCopy2 = Array.from(fruits);
// ["Strawberry", "Mango"]
// Create a copy using the slice() method.
const fruitsCopy3 = fruits.slice();
// ["Strawberry", "Mango"]
```
All built-in array-copy operations ([spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax), [`Array.from()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from), [`Array.prototype.slice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice), and [`Array.prototype.concat()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat)) create [shallow copies](/en-US/docs/Glossary/Shallow_copy). If you instead want a [deep copy](/en-US/docs/Glossary/Deep_copy) of an array, you can use {{jsxref("JSON.stringify()")}} to convert the array to a JSON string, and then {{jsxref("JSON.parse()")}} to convert the string back into a new array that's completely independent from the original array.
```js
const fruitsDeepCopy = JSON.parse(JSON.stringify(fruits));
```
You can also create deep copies using the [`structuredClone()`](/en-US/docs/Web/API/structuredClone) method, which has the advantage of allowing [transferable objects](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) in the source to be _transferred_ to the new copy, rather than just cloned.
Finally, it's important to understand that assigning an existing array to a new variable doesn't create a copy of either the array or its elements. Instead the new variable is just a reference, or alias, to the original array; that is, the original array's name and the new variable name are just two names for the exact same object (and so will always evaluate as [strictly equivalent](/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#strict_equality_using)). Therefore, if you make any changes at all either to the value of the original array or to the value of the new variable, the other will change, too:
```js
const fruits = ["Strawberry", "Mango"];
const fruitsAlias = fruits;
// 'fruits' and 'fruitsAlias' are the same object, strictly equivalent.
fruits === fruitsAlias; // true
// Any changes to the 'fruits' array change 'fruitsAlias' too.
fruits.unshift("Apple", "Banana");
console.log(fruits);
// ['Apple', 'Banana', 'Strawberry', 'Mango']
console.log(fruitsAlias);
// ['Apple', 'Banana', 'Strawberry', 'Mango']
```
### Creating a two-dimensional array
The following creates a chessboard as a two-dimensional array of strings. The first move is made by copying the `'p'` in `board[6][4]` to `board[4][4]`. The old position at `[6][4]` is made blank.
```js
const board = [
["R", "N", "B", "Q", "K", "B", "N", "R"],
["P", "P", "P", "P", "P", "P", "P", "P"],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "],
["p", "p", "p", "p", "p", "p", "p", "p"],
["r", "n", "b", "q", "k", "b", "n", "r"],
];
console.log(`${board.join("\n")}\n\n`);
// Move King's Pawn forward 2
board[4][4] = board[6][4];
board[6][4] = " ";
console.log(board.join("\n"));
```
Here is the output:
```plain
R,N,B,Q,K,B,N,R
P,P,P,P,P,P,P,P
, , , , , , ,
, , , , , , ,
, , , , , , ,
, , , , , , ,
p,p,p,p,p,p,p,p
r,n,b,q,k,b,n,r
R,N,B,Q,K,B,N,R
P,P,P,P,P,P,P,P
, , , , , , ,
, , , , , , ,
, , , ,p, , ,
, , , , , , ,
p,p,p,p, ,p,p,p
r,n,b,q,k,b,n,r
```
### Using an array to tabulate a set of values
```js
const values = [];
for (let x = 0; x < 10; x++) {
values.push([2 ** x, 2 * x ** 2]);
}
console.table(values);
```
Results in
```plain
// The first column is the index
0 1 0
1 2 2
2 4 8
3 8 18
4 16 32
5 32 50
6 64 72
7 128 98
8 256 128
9 512 162
```
### Creating an array using the result of a match
The result of a match between a {{jsxref("RegExp")}} and a string can create a JavaScript array that has properties and elements which provide information about the match. Such an array is returned by {{jsxref("RegExp.prototype.exec()")}} and {{jsxref("String.prototype.match()")}}.
For example:
```js
// Match one d followed by one or more b's followed by one d
// Remember matched b's and the following d
// Ignore case
const myRe = /d(b+)(d)/i;
const execResult = myRe.exec("cdbBdbsbz");
console.log(execResult.input); // 'cdbBdbsbz'
console.log(execResult.index); // 1
console.log(execResult); // [ "dbBd", "bB", "d" ]
```
For more information about the result of a match, see the {{jsxref("RegExp.prototype.exec()")}} and {{jsxref("String.prototype.match()")}} pages.
### Mutating initial array in iterative methods
[Iterative methods](#iterative_methods) do not mutate the array on which it is called, but the function provided as `callbackFn` can. The key principle to remember is that only indexes between 0 and `arrayLength - 1` are visited, where `arrayLength` is the length of the array at the time the array method was first called, but the element passed to the callback is the value at the time the index is visited. Therefore:
- `callbackFn` will not visit any elements added beyond the array's initial length when the call to the iterative method began.
- Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again.
- If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. Removed elements are not visited.
> **Warning:** Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).
The following examples use the `forEach` method as an example, but other methods that visit indexes in ascending order work in the same way. We will first define a helper function:
```js
function testSideEffect(effect) {
const arr = ["e1", "e2", "e3", "e4"];
arr.forEach((elem, index, arr) => {
console.log(`array: [${arr.join(", ")}], index: ${index}, elem: ${elem}`);
effect(arr, index);
});
console.log(`Final array: [${arr.join(", ")}]`);
}
```
Modification to indexes not visited yet will be visible once the index is reached:
```js
testSideEffect((arr, index) => {
if (index + 1 < arr.length) arr[index + 1] += "*";
});
// array: [e1, e2, e3, e4], index: 0, elem: e1
// array: [e1, e2*, e3, e4], index: 1, elem: e2*
// array: [e1, e2*, e3*, e4], index: 2, elem: e3*
// array: [e1, e2*, e3*, e4*], index: 3, elem: e4*
// Final array: [e1, e2*, e3*, e4*]
```
Modification to already visited indexes does not change iteration behavior, although the array will be different afterwards:
```js
testSideEffect((arr, index) => {
if (index > 0) arr[index - 1] += "*";
});
// array: [e1, e2, e3, e4], index: 0, elem: e1
// array: [e1, e2, e3, e4], index: 1, elem: e2
// array: [e1*, e2, e3, e4], index: 2, elem: e3
// array: [e1*, e2*, e3, e4], index: 3, elem: e4
// Final array: [e1*, e2*, e3*, e4]
```
Inserting _n_ elements at unvisited indexes that are less than the initial array length will make them be visited. The last _n_ elements in the original array that now have index greater than the initial array length will not be visited:
```js
testSideEffect((arr, index) => {
if (index === 1) arr.splice(2, 0, "new");
});
// array: [e1, e2, e3, e4], index: 0, elem: e1
// array: [e1, e2, e3, e4], index: 1, elem: e2
// array: [e1, e2, new, e3, e4], index: 2, elem: new
// array: [e1, e2, new, e3, e4], index: 3, elem: e3
// Final array: [e1, e2, new, e3, e4]
// e4 is not visited because it now has index 4
```
Inserting _n_ elements with index greater than the initial array length will not make them be visited:
```js
testSideEffect((arr) => arr.push("new"));
// array: [e1, e2, e3, e4], index: 0, elem: e1
// array: [e1, e2, e3, e4, new], index: 1, elem: e2
// array: [e1, e2, e3, e4, new, new], index: 2, elem: e3
// array: [e1, e2, e3, e4, new, new, new], index: 3, elem: e4
// Final array: [e1, e2, e3, e4, new, new, new, new]
```
Inserting _n_ elements at already visited indexes will not make them be visited, but it shifts remaining elements back by _n_, so the current index and the _n - 1_ elements before it are visited again:
```js
testSideEffect((arr, index) => arr.splice(index, 0, "new"));
// array: [e1, e2, e3, e4], index: 0, elem: e1
// array: [new, e1, e2, e3, e4], index: 1, elem: e1
// array: [new, new, e1, e2, e3, e4], index: 2, elem: e1
// array: [new, new, new, e1, e2, e3, e4], index: 3, elem: e1
// Final array: [new, new, new, new, e1, e2, e3, e4]
// e1 keeps getting visited because it keeps getting shifted back
```
Deleting _n_ elements at unvisited indexes will make them not be visited anymore. Because the array has shrunk, the last _n_ iterations will visit out-of-bounds indexes. If the method ignores non-existent indexes (see [array methods and empty slots](#array_methods_and_empty_slots)), the last _n_ iterations will be skipped; otherwise, they will receive `undefined`:
```js
testSideEffect((arr, index) => {
if (index === 1) arr.splice(2, 1);
});
// array: [e1, e2, e3, e4], index: 0, elem: e1
// array: [e1, e2, e3, e4], index: 1, elem: e2
// array: [e1, e2, e4], index: 2, elem: e4
// Final array: [e1, e2, e4]
// Does not visit index 3 because it's out-of-bounds
// Compare this with find(), which treats nonexistent indexes as undefined:
const arr2 = ["e1", "e2", "e3", "e4"];
arr2.find((elem, index, arr) => {
console.log(`array: [${arr.join(", ")}], index: ${index}, elem: ${elem}`);
if (index === 1) arr.splice(2, 1);
return false;
});
// array: [e1, e2, e3, e4], index: 0, elem: e1
// array: [e1, e2, e3, e4], index: 1, elem: e2
// array: [e1, e2, e4], index: 2, elem: e4
// array: [e1, e2, e4], index: 3, elem: undefined
```
Deleting _n_ elements at already visited indexes does not change the fact that they were visited before they get deleted. Because the array has shrunk, the next _n_ elements after the current index are skipped. If the method ignores non-existent indexes, the last _n_ iterations will be skipped; otherwise, they will receive `undefined`:
```js
testSideEffect((arr, index) => arr.splice(index, 1));
// array: [e1, e2, e3, e4], index: 0, elem: e1
// Does not visit e2 because e2 now has index 0, which has already been visited
// array: [e2, e3, e4], index: 1, elem: e3
// Does not visit e4 because e4 now has index 1, which has already been visited
// Final array: [e2, e4]
// Index 2 is out-of-bounds, so it's not visited
// Compare this with find(), which treats nonexistent indexes as undefined:
const arr2 = ["e1", "e2", "e3", "e4"];
arr2.find((elem, index, arr) => {
console.log(`array: [${arr.join(", ")}], index: ${index}, elem: ${elem}`);
arr.splice(index, 1);
return false;
});
// array: [e1, e2, e3, e4], index: 0, elem: e1
// array: [e2, e3, e4], index: 1, elem: e3
// array: [e2, e4], index: 2, elem: undefined
// array: [e2, e4], index: 3, elem: undefined
```
For methods that iterate in descending order of index, insertion causes elements to be skipped, and deletion causes elements to be visited multiple times. Adjust the code above yourself to see the effects.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("TypedArray")}}
- {{jsxref("ArrayBuffer")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/flatmap/index.md | ---
title: Array.prototype.flatMap()
slug: Web/JavaScript/Reference/Global_Objects/Array/flatMap
page-type: javascript-instance-method
browser-compat: javascript.builtins.Array.flatMap
---
{{JSRef}}
The **`flatMap()`** method of {{jsxref("Array")}} instances returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a {{jsxref("Array/map", "map()")}} followed by a {{jsxref("Array/flat", "flat()")}} of depth 1 (`arr.map(...args).flat()`), but slightly more efficient than calling those two methods separately.
{{EmbedInteractiveExample("pages/js/array-flatmap.html", "shorter")}}
## Syntax
```js-nolint
flatMap(callbackFn)
flatMap(callbackFn, thisArg)
```
### Parameters
- `callbackFn`
- : A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments:
- `element`
- : The current element being processed in the array.
- `index`
- : The index of the current element being processed in the array.
- `array`
- : The array `flatMap()` was called upon.
- `thisArg` {{optional_inline}}
- : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods).
### Return value
A new array with each element being the result of the callback function and flattened
by a depth of 1.
## Description
The `flatMap()` method is an [iterative method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). See {{jsxref("Array.prototype.map()")}} for a detailed description of the callback function. The `flatMap()` method is identical to [`map(callbackFn, thisArg)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) followed by [`flat(1)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) — for each element, it produces an array of new elements, and concatenates the resulting arrays together to form a new array. Read the [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods) section for more information about how these methods work in general.
The `flatMap()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. However, the value returned from `callbackFn` must be an array if it is to be flattened.
### Alternative
#### Pre-allocate and explicitly iterate
```js
const arr = [1, 2, 3, 4];
arr.flatMap((x) => [x, x * 2]);
// is equivalent to
const n = arr.length;
const acc = new Array(n * 2);
for (let i = 0; i < n; i++) {
const x = arr[i];
acc[i * 2] = x;
acc[i * 2 + 1] = x * 2;
}
// [1, 2, 2, 4, 3, 6, 4, 8]
```
Note that in this particular case the `flatMap` approach is slower than the
for-loop approach — due to the creation of temporary arrays that must be
garbage collected, as well as the return array not needing to be frequently
resized. However, `flatMap` may still be the correct solution in cases where
its flexibility and readability are desired.
## Examples
### map() and flatMap()
```js
const arr1 = [1, 2, 3, 4];
arr1.map((x) => [x * 2]);
// [[2], [4], [6], [8]]
arr1.flatMap((x) => [x * 2]);
// [2, 4, 6, 8]
// only one level is flattened
arr1.flatMap((x) => [[x * 2]]);
// [[2], [4], [6], [8]]
```
While the above could have been achieved by using map itself, here is an example that
better showcases the use of `flatMap()`.
Let's generate a list of words from a list of sentences.
```js
const arr1 = ["it's Sunny in", "", "California"];
arr1.map((x) => x.split(" "));
// [["it's","Sunny","in"],[""],["California"]]
arr1.flatMap((x) => x.split(" "));
// ["it's","Sunny","in", "", "California"]
```
Notice, the output list length can be different from the input list length.
### For adding and removing items during a map()
`flatMap` can be used as a way to add and remove items (modify the number of
items) during a `map`. In other words, it allows you to map _many items to
many items_ (by handling each input item separately), rather than always
_one-to-one_. In this sense, it works like the opposite of [filter](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter).
Return a 1-element array to keep the item, a multiple-element array to add items, or a
0-element array to remove the item.
```js
// Let's say we want to remove all the negative numbers
// and split the odd numbers into an even number and a 1
const a = [5, 4, -3, 20, 17, -33, -4, 18];
// |\ \ x | | \ x x |
// [4,1, 4, 20, 16, 1, 18]
const result = a.flatMap((n) => {
if (n < 0) {
return [];
}
return n % 2 === 0 ? [n] : [n - 1, 1];
});
console.log(result); // [4, 1, 4, 20, 16, 1, 18]
```
### Using the third argument of callbackFn
The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `filter()` to extract operational stations and then uses `flatMap()` to create a new array where each element contains a station and its next station. On the last station, it returns an empty array to exclude it from the final array.
```js
const stations = ["New Haven", "West Haven", "Milford (closed)", "Stratford"];
const line = stations
.filter((name) => !name.endsWith("(closed)"))
.flatMap((name, idx, arr) => {
// Without the arr argument, there's no way to easily access the
// intermediate array without saving it to a variable.
if (idx === arr.length - 1) return []; // last station has no next station
return [`${name} - ${arr[idx + 1]}`];
});
console.log(line); // ['New Haven - West Haven', 'West Haven - Stratford']
```
The `array` argument is _not_ the array that is being built — there is no way to access the array being built from the callback function.
### Using flatMap() on sparse arrays
The `callbackFn` won't be called for empty slots in the source array because `map()` doesn't, while `flat()` ignores empty slots in the returned arrays.
```js
console.log([1, 2, , 4, 5].flatMap((x) => [x, x * 2])); // [1, 2, 2, 4, 4, 8, 5, 10]
console.log([1, 2, 3, 4].flatMap((x) => [, x * 2])); // [2, 4, 6, 8]
```
### Calling flatMap() on non-array objects
The `flatMap()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. If the return value of the callback function is not an array, it is always directly appended to the result array.
```js
const arrayLike = {
length: 3,
0: 1,
1: 2,
2: 3,
3: 4, // ignored by flatMap() since length is 3
};
console.log(Array.prototype.flatMap.call(arrayLike, (x) => [x, x * 2]));
// [1, 2, 2, 4, 3, 6]
// Array-like objects returned from the callback won't be flattened
console.log(
Array.prototype.flatMap.call(arrayLike, (x) => ({
length: 1,
0: x,
})),
);
// [ { '0': 1, length: 1 }, { '0': 2, length: 1 }, { '0': 3, length: 1 } ]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Array.prototype.flatMap` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array")}}
- {{jsxref("Array.prototype.concat()")}}
- {{jsxref("Array.prototype.flat()")}}
- {{jsxref("Array.prototype.map()")}}
- {{jsxref("Array.prototype.reduce()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/at/index.md | ---
title: Array.prototype.at()
slug: Web/JavaScript/Reference/Global_Objects/Array/at
page-type: javascript-instance-method
browser-compat: javascript.builtins.Array.at
---
{{JSRef}}
The **`at()`** method of {{jsxref("Array")}} instances takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.
{{EmbedInteractiveExample("pages/js/array-at.html")}}
## Syntax
```js-nolint
at(index)
```
### Parameters
- `index`
- : Zero-based index of the array element to be returned, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). Negative index counts back from the end of the array — if `index < 0`, `index + array.length` is accessed.
### Return value
The element in the array matching the given index. Always returns {{jsxref("undefined")}} if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property.
## Description
The `at()` method is equivalent to the bracket notation when `index` is non-negative. For example, `array[0]` and `array.at(0)` both return the first item. However, when counting elements from the end of the array, you cannot use `array[-1]` like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading `array["-1"]`, which is just a normal string property instead of an array index.
The usual practice is to access {{jsxref("Array/length", "length")}} and calculate the index from that — for example, `array[array.length - 1]`. The `at()` method allows relative indexing, so this can be shortened to `array.at(-1)`.
By combining `at()` with {{jsxref("Array/with", "with()")}}, you can both read and write (respectively) an array using negative indices.
The `at()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
## Examples
### Return the last value of an array
The following example provides a function which returns the last element found in a specified array.
```js
// Our array with items
const cart = ["apple", "banana", "pear"];
// A function which returns the last item of a given array
function returnLast(arr) {
return arr.at(-1);
}
// Get the last item of our array 'cart'
const item1 = returnLast(cart);
console.log(item1); // 'pear'
// Add an item to our 'cart' array
cart.push("orange");
const item2 = returnLast(cart);
console.log(item2); // 'orange'
```
### Comparing methods
This example compares different ways to select the penultimate (last but one) item of an {{jsxref("Array")}}. While all the methods shown below are valid, this example highlights the succinctness and readability of the `at()` method.
```js
// Our array with items
const colors = ["red", "green", "blue"];
// Using length property
const lengthWay = colors[colors.length - 2];
console.log(lengthWay); // 'green'
// Using slice() method. Note an array is returned
const sliceWay = colors.slice(-2, -1);
console.log(sliceWay[0]); // 'green'
// Using at() method
const atWay = colors.at(-2);
console.log(atWay); // 'green'
```
### Calling at() on non-array objects
The `at()` method reads the `length` property of `this` and calculates the index to access.
```js
const arrayLike = {
length: 2,
0: "a",
1: "b",
2: "c", // ignored by at() since length is 2
};
console.log(Array.prototype.at.call(arrayLike, 0)); // "a"
console.log(Array.prototype.at.call(arrayLike, 2)); // undefined
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Array.prototype.at` in `core-js`](https://github.com/zloirock/core-js#relative-indexing-method)
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array")}}
- {{jsxref("Array.prototype.findIndex()")}}
- {{jsxref("Array.prototype.indexOf()")}}
- {{jsxref("Array.prototype.with()")}}
- {{jsxref("TypedArray.prototype.at()")}}
- {{jsxref("String.prototype.at()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/reduceright/index.md | ---
title: Array.prototype.reduceRight()
slug: Web/JavaScript/Reference/Global_Objects/Array/reduceRight
page-type: javascript-instance-method
browser-compat: javascript.builtins.Array.reduceRight
---
{{JSRef}}
The **`reduceRight()`** method of {{jsxref("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 {{jsxref("Array.prototype.reduce()")}} for left-to-right.
{{EmbedInteractiveExample("pages/js/array-reduce-right.html")}}
## Syntax
```js-nolint
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_inline}}
- : 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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). 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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#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](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays).
Unlike other [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). 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()](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#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, {{jsxref("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](<https://en.wikipedia.org/wiki/Function_composition_(computer_science)>) 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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Array.prototype.reduceRight` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array")}}
- {{jsxref("Array.prototype.map()")}}
- {{jsxref("Array.prototype.flat()")}}
- {{jsxref("Array.prototype.flatMap()")}}
- {{jsxref("Array.prototype.reduce()")}}
- {{jsxref("TypedArray.prototype.reduceRight()")}}
- {{jsxref("Object.groupBy()")}}
- {{jsxref("Map.groupBy()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/map/index.md | ---
title: Array.prototype.map()
slug: Web/JavaScript/Reference/Global_Objects/Array/map
page-type: javascript-instance-method
browser-compat: javascript.builtins.Array.map
---
{{JSRef}}
The **`map()`** method of {{jsxref("Array")}} instances creates
a new array populated with the results of calling a provided function on
every element in the calling array.
{{EmbedInteractiveExample("pages/js/array-map.html")}}
## Syntax
```js-nolint
map(callbackFn)
map(callbackFn, thisArg)
```
### Parameters
- `callbackFn`
- : A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments:
- `element`
- : The current element being processed in the array.
- `index`
- : The index of the current element being processed in the array.
- `array`
- : The array `map()` was called upon.
- `thisArg` {{optional_inline}}
- : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods).
### Return value
A new array with each element being the result of the callback function.
## Description
The `map()` method is an [iterative method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array and constructs a new array from the results. Read the [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#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](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays).
The `map()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Since `map` builds a new array, calling it without using the returned array is an anti-pattern; use {{jsxref("Array/forEach", "forEach")}} or {{jsxref("Statements/for...of", "for...of")}} instead.
## Examples
### Mapping an array of numbers to an array of square roots
The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.
```js
const numbers = [1, 4, 9];
const roots = numbers.map((num) => Math.sqrt(num));
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]
```
### Using map to reformat objects in an array
The following code takes an array of objects and creates a new array containing the newly reformatted objects.
```js
const kvArray = [
{ key: 1, value: 10 },
{ key: 2, value: 20 },
{ key: 3, value: 30 },
];
const reformattedArray = kvArray.map(({ key, value }) => ({ [key]: value }));
console.log(reformattedArray); // [{ 1: 10 }, { 2: 20 }, { 3: 30 }]
console.log(kvArray);
// [
// { key: 1, value: 10 },
// { key: 2, value: 20 },
// { key: 3, value: 30 }
// ]
```
### Using parseInt() with map()
It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors. Consider:
```js
["1", "2", "3"].map(parseInt);
```
While one might expect `[1, 2, 3]`, the actual result is `[1, NaN, NaN]`.
{{jsxref("parseInt")}} is often used with one argument, but takes two. The first is an expression and the second is the radix to the callback function, `Array.prototype.map` passes 3 arguments: the element, the index, and the array. The third argument is ignored by {{jsxref("parseInt")}} — but _not_ the second one! This is the source of possible confusion.
Here is a concise example of the iteration steps:
```js
/* first iteration (index is 0): */ parseInt("1", 0); // 1
/* second iteration (index is 1): */ parseInt("2", 1); // NaN
/* third iteration (index is 2): */ parseInt("3", 2); // NaN
```
To solve this, define another function that only takes one argument:
```js
["1", "2", "3"].map((str) => parseInt(str, 10)); // [1, 2, 3]
```
You can also use the {{jsxref("Number")}} function, which only takes one argument:
```js
["1", "2", "3"].map(Number); // [1, 2, 3]
// But unlike parseInt(), Number() will also return a float or (resolved) exponential notation:
["1.1", "2.2e2", "3e300"].map(Number); // [1.1, 220, 3e+300]
// For comparison, if we use parseInt() on the array above:
["1.1", "2.2e2", "3e300"].map((str) => parseInt(str, 10)); // [1, 2, 3]
```
See [A JavaScript optional argument hazard](https://wirfs-brock.com/allen/posts/166) by Allen Wirfs-Brock for more discussions.
### Mapped array contains undefined
When {{jsxref("undefined")}} or nothing is returned, the resulting array contains `undefined`. If you want to delete the element instead, chain a {{jsxref("Array/filter", "filter()")}} method, or use the {{jsxref("Array/flatMap", "flatMap()")}} method and return an empty array to signify deletion.
```js
const numbers = [1, 2, 3, 4];
const filteredNumbers = numbers.map((num, index) => {
if (index < 3) {
return num;
}
});
// index goes from 0, so the filterNumbers are 1,2,3 and undefined.
// filteredNumbers is [1, 2, 3, undefined]
// numbers is still [1, 2, 3, 4]
```
### Side-effectful mapping
The callback can have side effects.
```js
const cart = [5, 15, 25];
let total = 0;
const withTax = cart.map((cost) => {
total += cost;
return cost * 1.2;
});
console.log(withTax); // [6, 18, 30]
console.log(total); // 45
```
This is not recommended, because copying methods are best used with pure functions. In this case, we can choose to iterate the array twice.
```js
const cart = [5, 15, 25];
const total = cart.reduce((acc, cost) => acc + cost, 0);
const withTax = cart.map((cost) => cost * 1.2);
```
Sometimes this pattern goes to its extreme and the _only_ useful thing that `map()` does is causing side effects.
```js
const products = [
{ name: "sports car" },
{ name: "laptop" },
{ name: "phone" },
];
products.map((product) => {
product.price = 100;
});
```
As mentioned previously, this is an anti-pattern. If you don't use the return value of `map()`, use `forEach()` or a `for...of` loop instead.
```js
products.forEach((product) => {
product.price = 100;
});
```
Or, if you want to create a new array instead:
```js
const productsWithPrice = products.map((product) => {
return { ...product, price: 100 };
});
```
### Using the third argument of callbackFn
The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `filter()` to extract the positive values and then uses `map()` to create a new array where each element is the average of its neighbors and itself.
```js
const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6];
const averaged = numbers
.filter((num) => num > 0)
.map((num, idx, arr) => {
// Without the arr argument, there's no way to easily access the
// intermediate array without saving it to a variable.
const prev = arr[idx - 1];
const next = arr[idx + 1];
let count = 1;
let total = num;
if (prev !== undefined) {
count++;
total += prev;
}
if (next !== undefined) {
count++;
total += next;
}
const average = total / count;
// Keep two decimal places
return Math.round(average * 100) / 100;
});
console.log(averaged); // [2, 2.67, 2, 3.33, 5, 5.33, 5.67, 4]
```
The `array` argument is _not_ the array that is being built — there is no way to access the array being built from the callback function.
### Using map() on sparse arrays
A sparse array remains sparse after `map()`. The indices of empty slots are still empty in the returned array, and the callback function won't be called on them.
```js
console.log(
[1, , 3].map((x, index) => {
console.log(`Visit ${index}`);
return x * 2;
}),
);
// Visit 0
// Visit 2
// [2, empty, 6]
```
### Calling map() on non-array objects
The `map()` 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 map() since length is 3
};
console.log(Array.prototype.map.call(arrayLike, (x) => x ** 2));
// [ 4, 9, 16 ]
```
This example shows how to iterate through a collection of objects collected by `querySelectorAll`. This is because `querySelectorAll` returns a `NodeList` (which is a collection of objects). In this case, we return all the selected `option`s' values on the screen:
```js
const elems = document.querySelectorAll("select option:checked");
const values = Array.prototype.map.call(elems, ({ value }) => value);
```
You can also use {{jsxref("Array.from()")}} to transform `elems` to an array, and then access the `map()` method.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Array.prototype.map` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array")}}
- {{jsxref("Array.prototype.forEach()")}}
- {{jsxref("Array.from()")}}
- {{jsxref("TypedArray.prototype.map()")}}
- {{jsxref("Map")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/from/index.md | ---
title: Array.from()
slug: Web/JavaScript/Reference/Global_Objects/Array/from
page-type: javascript-static-method
browser-compat: javascript.builtins.Array.from
---
{{JSRef}}
The **`Array.from()`** static method creates a new, shallow-copied `Array` instance from an [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or [array-like](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects) object.
{{EmbedInteractiveExample("pages/js/array-from.html", "shorter")}}
## Syntax
```js-nolint
Array.from(arrayLike)
Array.from(arrayLike, mapFn)
Array.from(arrayLike, mapFn, thisArg)
```
### Parameters
- `arrayLike`
- : An iterable or array-like object to convert to an array.
- `mapFn` {{optional_inline}}
- : 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. The function is called with the following arguments:
- `element`
- : The current element being processed in the array.
- `index`
- : The index of the current element being processed in the array.
- `thisArg` {{optional_inline}}
- : Value to use as `this` when executing `mapFn`.
### Return value
A new {{jsxref("Array")}} instance.
## Description
`Array.from()` lets you create `Array`s from:
- [iterable objects](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) (objects such as {{jsxref("Map")}} and {{jsxref("Set")}}); or, if the object is not iterable,
- array-like objects (objects with a `length` property and indexed elements).
To convert an ordinary object that's not iterable or array-like to an array (by enumerating its property keys, values, or both), use {{jsxref("Object.keys()")}}, {{jsxref("Object.values()")}}, or {{jsxref("Object.entries()")}}. To convert an [async iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) to an array, use {{jsxref("Array.fromAsync()")}}.
`Array.from()` never creates a sparse array. If the `arrayLike` object is missing some index properties, they become `undefined` in the new array.
`Array.from()` has an optional parameter `mapFn`, which allows you to execute a function on each element of the array being created, similar to {{jsxref("Array/map", "map()")}}. More clearly, `Array.from(obj, mapFn, thisArg)` has the same result as `Array.from(obj).map(mapFn, thisArg)`, except that it does not create an intermediate array, and `mapFn` only receives two arguments (`element`, `index`) without the whole array, because the array is still under construction.
> **Note:** This behavior is more important for [typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays), since the intermediate array would necessarily have values truncated to fit into the appropriate type. `Array.from()` is implemented to have the same signature as {{jsxref("TypedArray.from()")}}.
The `Array.from()` method is a generic factory method. For example, if a subclass of `Array` inherits the `from()` method, the inherited `from()` 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. When an iterable is passed as `arrayLike`, the constructor is called with no arguments; when an array-like object is passed, the constructor is called with the [normalized length](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#normalization_of_the_length_property) of the array-like object. The final `length` will be set again when iteration finishes. If the `this` value is not a constructor function, the plain `Array` constructor is used instead.
## Examples
### Array from a String
```js
Array.from("foo");
// [ "f", "o", "o" ]
```
### Array from a Set
```js
const set = new Set(["foo", "bar", "baz", "foo"]);
Array.from(set);
// [ "foo", "bar", "baz" ]
```
### Array from a Map
```js
const map = new Map([
[1, 2],
[2, 4],
[4, 8],
]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]
const mapper = new Map([
["1", "a"],
["2", "b"],
]);
Array.from(mapper.values());
// ['a', 'b'];
Array.from(mapper.keys());
// ['1', '2'];
```
### Array from a NodeList
```js
// Create an array based on a property of DOM Elements
const images = document.querySelectorAll("img");
const sources = Array.from(images, (image) => image.src);
const insecureSources = sources.filter((link) => link.startsWith("http://"));
```
### Array from an Array-like object (arguments)
```js
function f() {
return Array.from(arguments);
}
f(1, 2, 3);
// [ 1, 2, 3 ]
```
### Using arrow functions and Array.from()
```js
// Using an arrow function as the map function to
// manipulate the elements
Array.from([1, 2, 3], (x) => x + x);
// [2, 4, 6]
// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
Array.from({ length: 5 }, (v, i) => i);
// [0, 1, 2, 3, 4]
```
### Sequence generator (range)
```js
// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP, etc.)
const range = (start, stop, step) =>
Array.from({ length: (stop - start) / step + 1 }, (_, i) => start + i * step);
// Generate numbers range 0..4
range(0, 4, 1);
// [0, 1, 2, 3, 4]
// Generate numbers range 1..10 with step of 2
range(1, 10, 2);
// [1, 3, 5, 7, 9]
// Generate the alphabet using Array.from making use of it being ordered as a sequence
range("A".charCodeAt(0), "Z".charCodeAt(0), 1).map((x) =>
String.fromCharCode(x),
);
// ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
```
### Calling from() on non-array constructors
The `from()` 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);
}
// Iterable
console.log(Array.from.call(NotArray, new Set(["foo", "bar", "baz"])));
// NotArray called with length undefined
// NotArray { '0': 'foo', '1': 'bar', '2': 'baz', length: 3 }
// Array-like
console.log(Array.from.call(NotArray, { length: 1, 0: "foo" }));
// NotArray called with length 1
// NotArray { '0': 'foo', length: 1 }
```
When the `this` value is not a constructor, a plain `Array` object is returned.
```js
console.log(Array.from.call({}, { length: 1, 0: "foo" })); // [ 'foo' ]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Array.from` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array")}}
- {{jsxref("Array/Array", "Array()")}}
- {{jsxref("Array.of()")}}
- {{jsxref("Array.fromAsync()")}}
- {{jsxref("Array.prototype.map()")}}
- {{jsxref("TypedArray.from()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/reverse/index.md | ---
title: Array.prototype.reverse()
slug: Web/JavaScript/Reference/Global_Objects/Array/reverse
page-type: javascript-instance-method
browser-compat: javascript.builtins.Array.reverse
---
{{JSRef}}
The **`reverse()`** method of {{jsxref("Array")}} instances reverses an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ 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 {{jsxref("Array/toReversed", "toReversed()")}}.
{{EmbedInteractiveExample("pages/js/array-reverse.html")}}
## Syntax
```js-nolint
reverse()
```
### Parameters
None.
### Return value
The reference to the original array, now reversed. Note that the array is reversed _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, 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](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the empty slots' corresponding new indices are [deleted](/en-US/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots.
The `reverse()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). 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](/en-US/docs/Glossary/Shallow_copy) array like other array methods (e.g. [`map()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)) do, use the {{jsxref("Array/toReversed", "toReversed()")}} method. Alternatively, you can do a shallow copy before calling `reverse()`, using the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) or [`Array.from()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/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](/en-US/docs/Web/JavaScript/Reference/Operators/delete) 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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Array.prototype.reverse` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array")}}
- {{jsxref("Array.prototype.join()")}}
- {{jsxref("Array.prototype.sort()")}}
- {{jsxref("Array.prototype.toReversed()")}}
- {{jsxref("TypedArray.prototype.reverse()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/copywithin/index.md | ---
title: Array.prototype.copyWithin()
slug: Web/JavaScript/Reference/Global_Objects/Array/copyWithin
page-type: javascript-instance-method
browser-compat: javascript.builtins.Array.copyWithin
---
{{JSRef}}
The **`copyWithin()`** method of {{jsxref("Array")}} instances shallow copies part of this array to another location in the same array and returns this array without modifying its length.
{{EmbedInteractiveExample("pages/js/array-copywithin.html")}}
## Syntax
```js-nolint
copyWithin(target, start)
copyWithin(target, start, end)
```
### Parameters
- `target`
- : Zero-based index at which to copy the sequence to, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). 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 `-array.length <= 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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion).
- Negative index counts back from the end of the array — if `-array.length <= start < 0`, `start + array.length` is used.
- If `start < -array.length`, `0` is used.
- If `start >= array.length`, nothing is copied.
- `end` {{optional_inline}}
- : Zero-based index at which to end copying elements from, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). `copyWithin()` copies up to but not including `end`.
- Negative index counts back from the end of the array — if `-array.length <= 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` implies a position before or at the position that `start` implies, 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 {{jsxref("Array")}}. This especially applies to the {{jsxref("TypedArray/copyWithin", "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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods). 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](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the empty slots' corresponding new indices are [deleted](/en-US/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots.
The `copyWithin()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). 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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Array.prototype.copyWithin` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array")}}
- {{jsxref("TypedArray.prototype.copyWithin()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/tostring/index.md | ---
title: Array.prototype.toString()
slug: Web/JavaScript/Reference/Global_Objects/Array/toString
page-type: javascript-instance-method
browser-compat: javascript.builtins.Array.toString
---
{{JSRef}}
The **`toString()`** method of {{jsxref("Array")}} instances returns a string representing the
specified array and its elements.
{{EmbedInteractiveExample("pages/js/array-tostring.html", "shorter")}}
## Syntax
```js-nolint
toString()
```
### Parameters
None.
### Return value
A string representing the elements of the array.
## Description
The {{jsxref("Array")}} object overrides the `toString` method of {{jsxref("Object")}}. The `toString` method of arrays calls [`join()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) internally, which joins the array and returns one string containing each array element separated by commas. If the `join` method is unavailable or is not a function, [`Object.prototype.toString`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString) is used instead, returning `[object Array]`.
```js
const arr = [];
arr.join = 1; // re-assign `join` with a non-function
console.log(arr.toString()); // [object Array]
console.log(Array.prototype.toString.call({ join: () => 1 })); // 1
```
JavaScript calls the `toString` method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.
`Array.prototype.toString` recursively converts each element, including other arrays, to strings. Because the string returned by `Array.prototype.toString` does not have delimiters, nested arrays look like they are flattened.
```js
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
console.log(matrix.toString()); // 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.toString()); // 1,3,,4,2
```
## Examples
### Using toString()
```js
const array1 = [1, 2, "a", "1a"];
console.log(array1.toString()); // "1,2,a,1a"
```
### Using toString() on sparse arrays
Following the behavior of `join()`, `toString()` treats empty slots the same as `undefined` and produces an extra separator:
```js
console.log([1, , 3].toString()); // '1,,3'
```
### Calling toString() on non-array objects
`toString()` is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It expects `this` to have a `join()` method; or, failing that, uses `Object.prototype.toString()` instead.
```js
console.log(Array.prototype.toString.call({ join: () => 1 }));
// 1; a number
console.log(Array.prototype.toString.call({ join: () => undefined }));
// undefined
console.log(Array.prototype.toString.call({ join: "not function" }));
// "[object Object]"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array")}}
- {{jsxref("Array.prototype.join()")}}
- {{jsxref("Array.prototype.toLocaleString()")}}
- {{jsxref("TypedArray.prototype.toString()")}}
- {{jsxref("String.prototype.toString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/slice/index.md | ---
title: Array.prototype.slice()
slug: Web/JavaScript/Reference/Global_Objects/Array/slice
page-type: javascript-instance-method
browser-compat: javascript.builtins.Array.slice
---
{{JSRef}}
The **`slice()`** method of {{jsxref("Array")}} instances returns a [shallow copy](/en-US/docs/Glossary/Shallow_copy) of a portion of
an array into a new array object selected from `start` to `end`
(`end` not included) where `start` and `end` represent
the index of items in that array. The original array will not be modified.
{{EmbedInteractiveExample("pages/js/array-slice.html", "taller")}}
## Syntax
```js-nolint
slice()
slice(start)
slice(start, end)
```
### Parameters
- `start` {{optional_inline}}
- : Zero-based index at which to start extraction, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion).
- Negative index counts back from the end of the array — if `-array.length <= start < 0`, `start + array.length` is used.
- If `start < -array.length` or `start` is omitted, `0` is used.
- If `start >= array.length`, nothing is extracted.
- `end` {{optional_inline}}
- : Zero-based index at which to end extraction, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). `slice()` extracts up to but not including `end`.
- Negative index counts back from the end of the array — if `-array.length <= 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 extracted.
- If `end` implies a position before or at the position that `start` implies, nothing is extracted.
### Return value
A new array containing the extracted elements.
## Description
The `slice()` method is a [copying method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods). It does not alter `this` but instead returns a [shallow copy](/en-US/docs/Glossary/Shallow_copy) that contains some of the same elements as the ones from the original array.
The `slice()` method preserves empty slots. If the sliced portion is [sparse](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the returned array is sparse as well.
The `slice()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
## Examples
### Return a portion of an existing array
```js
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1, 3);
// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']
```
### Using slice
In the following example, `slice` creates a new array, `newCar`,
from `myCar`. Both include a reference to the object `myHonda`.
When the color of `myHonda` is changed to purple, both arrays reflect the
change.
```js
// Using slice, create newCar from myCar.
const myHonda = {
color: "red",
wheels: 4,
engine: { cylinders: 4, size: 2.2 },
};
const myCar = [myHonda, 2, "cherry condition", "purchased 1997"];
const newCar = myCar.slice(0, 2);
console.log("myCar =", myCar);
console.log("newCar =", newCar);
console.log("myCar[0].color =", myCar[0].color);
console.log("newCar[0].color =", newCar[0].color);
// Change the color of myHonda.
myHonda.color = "purple";
console.log("The new color of my Honda is", myHonda.color);
console.log("myCar[0].color =", myCar[0].color);
console.log("newCar[0].color =", newCar[0].color);
```
This script writes:
```plain
myCar = [
{ color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } },
2,
'cherry condition',
'purchased 1997'
]
newCar = [ { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }, 2 ]
myCar[0].color = red
newCar[0].color = red
The new color of my Honda is purple
myCar[0].color = purple
newCar[0].color = purple
```
### Calling slice() on non-array objects
The `slice()` method reads the `length` property of `this`. It then reads the integer-keyed properties from `start` to `end` and defines them on a newly created array.
```js
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 4,
3: 33, // ignored by slice() since length is 3
};
console.log(Array.prototype.slice.call(arrayLike, 1, 3));
// [ 3, 4 ]
```
### Using slice() to convert array-like objects to arrays
The `slice()` method is often used with {{jsxref("Function/bind", "bind()")}} and {{jsxref("Function/call", "call()")}} to create a utility method that converts an array-like object into an array.
```js
// slice() is called with `this` passed as the first argument
const slice = Function.prototype.call.bind(Array.prototype.slice);
function list() {
return slice(arguments);
}
const list1 = list(1, 2, 3); // [1, 2, 3]
```
### Using slice() on sparse arrays
The array returned from `slice()` may be sparse if the source is sparse.
```js
console.log([1, 2, , 4, 5].slice(1, 4)); // [2, empty, 4]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Array.prototype.slice` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array")}}
- {{jsxref("Array.prototype.pop()")}}
- {{jsxref("Array.prototype.shift()")}}
- {{jsxref("Array.prototype.concat()")}}
- {{jsxref("Array.prototype.splice()")}}
- {{jsxref("TypedArray.prototype.slice()")}}
- {{jsxref("String.prototype.slice()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/findlast/index.md | ---
title: Array.prototype.findLast()
slug: Web/JavaScript/Reference/Global_Objects/Array/findLast
page-type: javascript-instance-method
browser-compat: javascript.builtins.Array.findLast
---
{{JSRef}}
The **`findLast()`** method of {{jsxref("Array")}} instances iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function.
If no elements satisfy the testing function, {{jsxref("undefined")}} is returned.
If you need to find:
- the _first_ element that matches, use {{jsxref("Array/find", "find()")}}.
- the _index_ of the last matching element in the array, use {{jsxref("Array/findLastIndex", "findLastIndex()")}}.
- the _index of a value_, use {{jsxref("Array/indexOf", "indexOf()")}}.
(It's similar to {{jsxref("Array/findIndex", "findIndex()")}}, but checks each element for equality with the value instead of using a testing function.)
- whether a value _exists_ in an array, use {{jsxref("Array/includes", "includes()")}}.
Again, it checks each element for equality with the value instead of using a testing function.
- if any element satisfies the provided testing function, use {{jsxref("Array/some", "some()")}}.
{{EmbedInteractiveExample("pages/js/array-findlast.html", "shorter")}}
## Syntax
```js-nolint
findLast(callbackFn)
findLast(callbackFn, thisArg)
```
### Parameters
- `callbackFn`
- : A function to execute for each element in the array. It should return a [truthy](/en-US/docs/Glossary/Truthy) value to indicate a matching element has been found, and a [falsy](/en-US/docs/Glossary/Falsy) value otherwise. The function is called with the following arguments:
- `element`
- : The current element being processed in the array.
- `index`
- : The index of the current element being processed in the array.
- `array`
- : The array `findLast()` was called upon.
- `thisArg` {{optional_inline}}
- : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods).
### Return value
The last (highest-index) element in the array that satisfies the provided testing function; {{jsxref("undefined")}} if no matching element is found.
## Description
The `findLast()` method is an [iterative method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array in descending-index order, until `callbackFn` returns a [truthy](/en-US/docs/Glossary/Truthy) value. `findLast()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findLast()` returns {{jsxref("undefined")}}. Read the [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods) section for more information about how these methods work in general.
`callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) behave the same as `undefined`.
The `findLast()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
## Examples
### Find last object in an array matching on element properties
This example shows how you might create a test based on the properties of array elements.
```js
const inventory = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "fish", quantity: 1 },
{ name: "cherries", quantity: 5 },
];
// return true inventory stock is low
function isNotEnough(item) {
return item.quantity < 2;
}
console.log(inventory.findLast(isNotEnough));
// { name: "fish", quantity: 1 }
```
#### Using arrow function and destructuring
The previous example might be written using an arrow function and [object destructuring](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#object_destructuring):
```js
const inventory = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "fish", quantity: 1 },
{ name: "cherries", quantity: 5 },
];
const result = inventory.findLast(({ quantity }) => quantity < 2);
console.log(result);
// { name: "fish", quantity: 1 }
```
### Find the last prime number in an array
The following example returns the last element in the array that is a prime number, or {{jsxref("undefined")}} if there is no prime number.
```js
function isPrime(element) {
if (element % 2 === 0 || element < 2) {
return false;
}
for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {
if (element % factor === 0) {
return false;
}
}
return true;
}
console.log([4, 6, 8, 12].findLast(isPrime)); // undefined, not found
console.log([4, 5, 7, 8, 9, 11, 12].findLast(isPrime)); // 11
```
### Using the third argument of callbackFn
The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `filter()` to extract the positive values and then uses `findLast()` to find the last element that is less than its neighbors.
```js
const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6];
const lastTrough = numbers
.filter((num) => num > 0)
.findLast((num, idx, arr) => {
// Without the arr argument, there's no way to easily access the
// intermediate array without saving it to a variable.
if (idx > 0 && num >= arr[idx - 1]) return false;
if (idx < arr.length - 1 && num >= arr[idx + 1]) return false;
return true;
});
console.log(lastTrough); // 2
```
### Using findLast() on sparse arrays
Empty slots in sparse arrays _are_ visited, and are treated the same as `undefined`.
```js
// Declare array with no elements at indexes 2, 3, and 4
const array = [0, 1, , , , 5, 6];
// Shows all indexes, not just those with assigned values
array.findLast((value, index) => {
console.log(`Visited index ${index} with value ${value}`);
});
// Visited index 6 with value 6
// Visited index 5 with value 5
// Visited index 4 with value undefined
// Visited index 3 with value undefined
// Visited index 2 with value undefined
// Visited index 1 with value 1
// Visited index 0 with value 0
// Shows all indexes, including deleted
array.findLast((value, index) => {
// Delete element 5 on first iteration
if (index === 6) {
console.log(`Deleting array[5] with value ${array[5]}`);
delete array[5];
}
// Element 5 is still visited even though deleted
console.log(`Visited index ${index} with value ${value}`);
});
// Deleting array[5] with value 5
// Visited index 6 with value 6
// Visited index 5 with value undefined
// Visited index 4 with value undefined
// Visited index 3 with value undefined
// Visited index 2 with value undefined
// Visited index 1 with value 1
// Visited index 0 with value 0
```
### Calling findLast() on non-array objects
The `findLast()` 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: 7.3,
2: 4,
3: 3, // ignored by findLast() since length is 3
};
console.log(
Array.prototype.findLast.call(arrayLike, (x) => Number.isInteger(x)),
); // 4
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Array.prototype.findLast` in `core-js`](https://github.com/zloirock/core-js#array-find-from-last)
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array")}}
- {{jsxref("Array.prototype.find()")}}
- {{jsxref("Array.prototype.findIndex()")}}
- {{jsxref("Array.prototype.findLastIndex()")}}
- {{jsxref("Array.prototype.includes()")}}
- {{jsxref("Array.prototype.filter()")}}
- {{jsxref("Array.prototype.every()")}}
- {{jsxref("Array.prototype.some()")}}
- {{jsxref("TypedArray.prototype.findLast()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/includes/index.md | ---
title: Array.prototype.includes()
slug: Web/JavaScript/Reference/Global_Objects/Array/includes
page-type: javascript-instance-method
browser-compat: javascript.builtins.Array.includes
---
{{JSRef}}
The **`includes()`** method of {{jsxref("Array")}} instances determines whether an array
includes a certain value among its entries, returning `true` or
`false` as appropriate.
{{EmbedInteractiveExample("pages/js/array-includes.html")}}
## Syntax
```js-nolint
includes(searchElement)
includes(searchElement, fromIndex)
```
### Parameters
- `searchElement`
- : The value to search for.
- `fromIndex` {{optional_inline}}
- : Zero-based index at which to start searching, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion).
- Negative index counts back from the end of the array — if `-array.length <= fromIndex < 0`, `fromIndex + array.length` is used. However, the array is still searched from front to back in this case.
- If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched.
- If `fromIndex >= array.length`, the array is not searched and `false` is returned.
### Return value
A boolean value which is `true` if the value `searchElement` is found within the array (or the part of the array indicated by the index `fromIndex`, if specified).
## Description
The `includes()` method compares `searchElement` to elements of the array using the [SameValueZero](/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value-zero_equality) algorithm. Values of zero are all considered to be equal, regardless of sign. (That is, `-0` is equal to `0`), but `false` is _not_ considered to be the same as `0`. [`NaN`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN) can be correctly searched for.
When used on [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the `includes()` method iterates empty slots as if they have the value `undefined`.
The `includes()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
## Examples
### Using includes()
```js
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true
["1", "2", "3"].includes(3); // false
```
### fromIndex is greater than or equal to the array length
If `fromIndex` is greater than or equal to the length of the
array, `false` is returned. The array will not be searched.
```js
const arr = ["a", "b", "c"];
arr.includes("c", 3); // false
arr.includes("c", 100); // false
```
### Computed index is less than 0
If `fromIndex` is negative, the computed index is calculated to
be used as a position in the array at which to begin searching for
`searchElement`. If the computed index is less than or equal to
`0`, the entire array will be searched.
```js
// array length is 3
// fromIndex is -100
// computed index is 3 + (-100) = -97
const arr = ["a", "b", "c"];
arr.includes("a", -100); // true
arr.includes("b", -100); // true
arr.includes("c", -100); // true
arr.includes("a", -2); // false
```
### Using includes() on sparse arrays
You can search for `undefined` in a sparse array and get `true`.
```js
console.log([1, , 3].includes(undefined)); // true
```
### Calling includes() on non-array objects
The `includes()` 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: 1, // ignored by includes() since length is 3
};
console.log(Array.prototype.includes.call(arrayLike, 2));
// true
console.log(Array.prototype.includes.call(arrayLike, 1));
// false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Array.prototype.includes` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array")}}
- {{jsxref("Array.prototype.indexOf()")}}
- {{jsxref("Array.prototype.find()")}}
- {{jsxref("Array.prototype.findIndex()")}}
- {{jsxref("TypedArray.prototype.includes()")}}
- {{jsxref("String.prototype.includes()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/toreversed/index.md | ---
title: Array.prototype.toReversed()
slug: Web/JavaScript/Reference/Global_Objects/Array/toReversed
page-type: javascript-instance-method
browser-compat: javascript.builtins.Array.toReversed
---
{{JSRef}}
The **`toReversed()`** method of {{jsxref("Array")}} instances is the [copying](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods) counterpart of the {{jsxref("Array/reverse", "reverse()")}} method. It returns a new array with the elements in reversed order.
## Syntax
```js-nolint
toReversed()
```
### Parameters
None.
### Return value
A new array containing the elements in reversed order.
## Description
The `toReversed()` method transposes the elements of the calling array object in reverse order and returns a new array.
When used on [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the `toReversed()` method iterates empty slots as if they have the value `undefined`.
The `toReversed()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
## Examples
### Reversing the elements in an array
The following example creates an array `items`, containing three elements, then creates a new array that's the reverse of `items`. The `items` array remains unchanged.
```js
const items = [1, 2, 3];
console.log(items); // [1, 2, 3]
const reversedItems = items.toReversed();
console.log(reversedItems); // [3, 2, 1]
console.log(items); // [1, 2, 3]
```
### Using toReversed() on sparse arrays
The return value of `toReversed()` is never sparse. Empty slots become `undefined` in the returned array.
```js
console.log([1, , 3].toReversed()); // [3, undefined, 1]
console.log([1, , 3, 4].toReversed()); // [4, 3, undefined, 1]
```
### Calling toReversed() on non-array objects
The `toReversed()` method reads the `length` property of `this`. It then visits each property having an integer key between `length - 1` and `0` in descending order, adding the value of the current property to the end of the array to be returned.
```js
const arrayLike = {
length: 3,
unrelated: "foo",
2: 4,
};
console.log(Array.prototype.toReversed.call(arrayLike));
// [4, undefined, undefined]
// The '0' and '1' indices are not present so they become undefined
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Array.prototype.toReversed` in `core-js`](https://github.com/zloirock/core-js#change-array-by-copy)
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array.prototype.reverse()")}}
- {{jsxref("Array.prototype.toSorted()")}}
- {{jsxref("Array.prototype.toSpliced()")}}
- {{jsxref("Array.prototype.with()")}}
- {{jsxref("TypedArray.prototype.toReversed()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/push/index.md | ---
title: Array.prototype.push()
slug: Web/JavaScript/Reference/Global_Objects/Array/push
page-type: javascript-instance-method
browser-compat: javascript.builtins.Array.push
---
{{JSRef}}
The **`push()`** method of {{jsxref("Array")}} instances adds the specified elements to the end of
an array and returns the new length of the array.
{{EmbedInteractiveExample("pages/js/array-push.html")}}
## Syntax
```js-nolint
push()
push(element1)
push(element1, element2)
push(element1, element2, /* …, */ elementN)
```
### Parameters
- `element1`, …, `elementN`
- : The element(s) to add to the end of the array.
### Return value
The new {{jsxref("Array/length", "length")}} property of the object upon which the method was called.
## Description
The `push()` method appends values to an array.
{{jsxref("Array.prototype.unshift()")}} has similar behavior to `push()`, but applied to the start of an array.
The `push()` method is a [mutating method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods). 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 elements appended to the end, you can use [`arr.concat([element0, element1, /* ... ,*/ elementN])`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of `concat()`.
The `push()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). 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
### Adding elements to an array
The following code creates the `sports` array containing two elements, then
appends two elements to it. The `total` variable contains the new length of
the array.
```js
const sports = ["soccer", "baseball"];
const total = sports.push("football", "swimming");
console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
console.log(total); // 4
```
### Merging two arrays
This example uses {{jsxref("Operators/Spread_syntax", "spread syntax", "", "1")}} to push all elements from a
second array into the first one.
```js
const vegetables = ["parsnip", "potato"];
const moreVegs = ["celery", "beetroot"];
// Merge the second array into the first one
vegetables.push(...moreVegs);
console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']
```
Merging two arrays can also be done with the {{jsxref("Array/concat", "concat()")}} method.
### Calling push() on non-array objects
The `push()` method reads the `length` property of `this`. It then sets each index of `this` starting at `length` with the arguments passed to `push()`. Finally, it sets the `length` to the previous length plus the number of pushed elements.
```js
const arrayLike = {
length: 3,
unrelated: "foo",
2: 4,
};
Array.prototype.push.call(arrayLike, 1, 2);
console.log(arrayLike);
// { '2': 4, '3': 1, '4': 2, length: 5, unrelated: 'foo' }
const plainObj = {};
// There's no length property, so the length is 0
Array.prototype.push.call(plainObj, 1, 2);
console.log(plainObj);
// { '0': 1, '1': 2, length: 2 }
```
### Using an object in an array-like fashion
As mentioned above, `push` is intentionally generic, and we can use that to
our advantage. `Array.prototype.push` can work on an object just fine, as
this example shows.
Note that 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` to trick the method into thinking we are dealing with
an array—and it just works, thanks to the way JavaScript allows us to establish the
execution context in any way we want.
```js
const obj = {
length: 0,
addElem(elem) {
// obj.length is automatically incremented
// every time an element is added.
[].push.call(this, elem);
},
};
// Let's add some empty objects just to illustrate.
obj.addElem({});
obj.addElem({});
console.log(obj.length); // 2
```
Note that although `obj` is not an array, the method `push`
successfully incremented `obj`'s `length` property just like if we
were dealing with an actual array.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Array.prototype.push` in `core-js` with fixes of this method](https://github.com/zloirock/core-js#ecmascript-array)
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array")}}
- {{jsxref("Array.prototype.pop()")}}
- {{jsxref("Array.prototype.shift()")}}
- {{jsxref("Array.prototype.unshift()")}}
- {{jsxref("Array.prototype.concat()")}}
- {{jsxref("Array.prototype.splice()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/length/index.md | ---
title: "Array: length"
slug: Web/JavaScript/Reference/Global_Objects/Array/length
page-type: javascript-instance-data-property
browser-compat: javascript.builtins.Array.length
---
{{JSRef}}
The **`length`** data property of an {{jsxref("Array")}} instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
{{EmbedInteractiveExample("pages/js/array-length.html", "shorter")}}
## Value
A nonnegative integer less than 2<sup>32</sup>.
{{js_property_attributes(1, 0, 0)}}
## Description
The value of the `length` property is a nonnegative integer with a value less than 2<sup>32</sup>.
```js
const listA = [1, 2, 3];
const listB = new Array(6);
console.log(listA.length);
// 3
console.log(listB.length);
// 6
listB.length = 2 ** 32; // 4294967296
// RangeError: Invalid array length
const listC = new Array(-100); // Negative numbers are not allowed
// RangeError: Invalid array length
```
The array object observes the `length` property, and automatically syncs the `length` value with the array's content. This means:
- Setting `length` to a value smaller than the current length truncates the array — elements beyond the new `length` are deleted.
- Setting any array index (a nonnegative integer smaller than 2<sup>32</sup>) beyond the current `length` extends the array — the `length` property is increased to reflect the new highest index.
- Setting `length` to an invalid value (e.g. a negative number or a non-integer) throws a `RangeError` exception.
When `length` is set to a bigger value than the current length, the array is extended by adding [empty slots](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), not actual `undefined` values. Empty slots have some special interactions with array methods; see [array methods and empty slots](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#array_methods_and_empty_slots).
```js
const arr = [1, 2];
console.log(arr);
// [ 1, 2 ]
arr.length = 5; // set array length to 5 while currently 2.
console.log(arr);
// [ 1, 2, <3 empty items> ]
arr.forEach((element) => console.log(element));
// 1
// 2
```
See also [Relationship between `length` and numerical properties](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#relationship_between_length_and_numerical_properties).
## Examples
### Iterating over an array
In the following example, the array `numbers` is iterated through by looking at the `length` property. The value in each element is then doubled.
```js
const numbers = [1, 2, 3, 4, 5];
const length = numbers.length;
for (let i = 0; i < length; i++) {
numbers[i] *= 2;
}
// numbers is now [2, 4, 6, 8, 10]
```
### Shortening an array
The following example shortens the array `numbers` to a length of 3 if the current length is greater than 3.
```js
const numbers = [1, 2, 3, 4, 5];
if (numbers.length > 3) {
numbers.length = 3;
}
console.log(numbers); // [1, 2, 3]
console.log(numbers.length); // 3
console.log(numbers[3]); // undefined; the extra elements are deleted
```
### Create empty array of fixed length
Setting `length` to a value greater than the current length creates a [sparse array](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays).
```js
const numbers = [];
numbers.length = 3;
console.log(numbers); // [empty x 3]
```
### Array with non-writable length
The `length` property is automatically updated by the array when elements are added beyond the current length. If the `length` property is made non-writable, the array will not be able to update it. This causes an error in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode).
```js
"use strict";
const numbers = [1, 2, 3, 4, 5];
Object.defineProperty(numbers, "length", { writable: false });
numbers[5] = 6; // TypeError: Cannot assign to read only property 'length' of object '[object Array]'
numbers.push(5); // // TypeError: Cannot assign to read only property 'length' of object '[object Array]'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array")}}
- [`TypedArray.prototype.length`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/length)
- [`String`: `length`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length)
- [RangeError: invalid array length](/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length)
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.