parseFloat() - JavaScript

parseFloat()
============

The **`parseFloat()`** function parses a string argument and returns a floating point number.

Try it
------

Syntax
------

```js
parseFloat(string)
```

### Parameters

`string`

The value to parse, coerced to a string. Leading whitespace in this argument is ignored.

### Return value

A floating point number parsed from the given `string`, or `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()` 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 `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 `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 `NaN`.

Syntax-wise, `parseFloat()` parses a subset of the syntax that the `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 `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 `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
parseFloat(900719925474099267n); // 900719925474099300
parseFloat("900719925474099267n"); // 900719925474099300
```

You should pass the string to the `BigInt()` function instead, without the trailing `n` character.

```js
BigInt("900719925474099267");
// 900719925474099267n
```

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

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

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

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

See also
--------

* `parseInt()`
* `Number.parseFloat()`
* `Number.parseInt()`
* `Number.prototype.toFixed()`


TypeError - JavaScript

TypeError
=========

The **`TypeError`** object represents an error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type.

A `TypeError` may be thrown when:

* an operand or argument passed to a function is incompatible with the type expected by that operator or function; or
* when attempting to modify a value that cannot be changed; or
* when attempting to use a value in an inappropriate way.

`TypeError` is a serializable object, so it can be cloned with `structuredClone()` or copied between Workers using `postMessage()`.

`TypeError` is a subclass of `Error`.

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

`TypeError()`

Creates a new `TypeError` object.

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

*Also inherits instance properties from its parent `Error`*.

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

`TypeError.prototype.constructor`

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

`TypeError.prototype.name`

Represents the name for the type of error. For `TypeError.prototype.name`, the initial value is `"TypeError"`.

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

*Inherits instance methods from its parent `Error`*.

Examples
--------

### Catching a TypeError

```js
try {
  null.f();
} catch (e) {
  console.log(e instanceof TypeError); // true
  console.log(e.message); // "null has no properties"
  console.log(e.name); // "TypeError"
  console.log(e.stack); // Stack of the error
}
```

### Creating a TypeError

```js
try {
  throw new TypeError("Hello");
} catch (e) {
  console.log(e instanceof TypeError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "TypeError"
  console.log(e.stack); // Stack of the error
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-native-error-types-used-in-this-standard-typeerror |

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

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

See also
--------

* `Error`


Iterator - JavaScript

Iterator
========

An **`Iterator`** object is an object that conforms to the iterator protocol by providing a `next()` method that returns an iterator result object. All built-in iterators inherit from the `Iterator` class. The `Iterator` class provides a `@@iterator` method that returns the iterator object itself, making the iterator also iterable. It also provides some helper methods for working with iterators.

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

The following are all built-in JavaScript iterators:

* The *Array Iterator* returned by `Array.prototype.values()`, `Array.prototype.keys()`, `Array.prototype.entries()`, `Array.prototype[@@iterator]()`, `TypedArray.prototype.values()`, `TypedArray.prototype.keys()`, `TypedArray.prototype.entries()`, `TypedArray.prototype[@@iterator]()`, and `arguments[@@iterator]()`.
* The *String Iterator* returned by `String.prototype[@@iterator]()`.
* The *Map Iterator* returned by `Map.prototype.values()`, `Map.prototype.keys()`, `Map.prototype.entries()`, and `Map.prototype[@@iterator]()`.
* The *Set Iterator* returned by `Set.prototype.values()`, `Set.prototype.keys()`, `Set.prototype.entries()`, and `Set.prototype[@@iterator]()`.
* The *RegExp String Iterator* returned by `RegExp.prototype[@@matchAll]()` and `String.prototype.matchAll()`.
* The `Generator` object returned by generator functions.
* The *Segments Iterator* returned by the `[@@iterator]()` method of the `Segments` object returned by `Intl.Segmenter.prototype.segment()`.
* The *Iterator Helper* returned by iterator helper methods such as `Iterator.prototype.filter()` and `Iterator.prototype.map()`.

Each of these iterators have a distinct prototype object, which defines the `next()` method used by the particular iterator. For example, all string iterator objects inherit from a hidden object `StringIteratorPrototype`, which has a `next()` method that iterates this string by code points. `StringIteratorPrototype` also has a `@@toStringTag` property whose initial value is the string `"String Iterator"`. This property is used in `Object.prototype.toString()`. Similarly, other iterator prototypes also have their own `@@toStringTag` values, which are the same as the names given above.

All of these prototype objects inherit from `Iterator.prototype`, which provides a `@@iterator` method that returns the iterator object itself, making the iterator also iterable.

### Iterator helpers

**Note:** These methods are *iterator* helpers, not *iterable* helpers, because the only requirement for an object to be iterable is just the presence of a `@@iterator` method. There is no shared prototype to install these methods on.

The `Iterator` class itself provides some helper methods for working with iterators. For example, you may be tempted to do the following:

```js
const nameToDeposit = new Map([
  ["Anne", 1000],
  ["Bert", 1500],
  ["Carl", 2000],
]);

const totalDeposit = [...nameToDeposit.values()].reduce((a, b) => a + b);
```

This first converts the iterator returned by `Map.prototype.values()` to an array, then uses the `Array.prototype.reduce()` method to calculate the sum. However, this both creates an intermediate array and iterates the array twice. Instead, you can use the `reduce()` method of the iterator itself:

```js
const totalDeposit = nameToDeposit.values().reduce((a, b) => a + b);
```

This method is more efficient, because it only iterates the iterator once, without memorizing any intermediate values. Iterator helper methods are necessary to work with infinite iterators:

```js
function\* fibonacci() {
  let current = 1;
  let next = 1;
  while (true) {
    yield current;
    [current, next] = [next, current + next];
  }
}

const seq = fibonacci();
const firstThreeDigitTerm = seq.find((n) => n >= 100);
```

You cannot convert `seq` to an array, because it is infinite. Instead, you can use the `find()` method of the iterator itself, which only iterates `seq` as far as necessary to find the first value that satisfies the condition.

You will find many iterator methods analogous to array methods, such as:

| Iterator method | Array method |
| --- | --- |
| `Iterator.prototype.every()` | `Array.prototype.every()` |
| `Iterator.prototype.filter()` | `Array.prototype.filter()` |
| `Iterator.prototype.find()` | `Array.prototype.find()` |
| `Iterator.prototype.flatMap()` | `Array.prototype.flatMap()` |
| `Iterator.prototype.forEach()` | `Array.prototype.forEach()` |
| `Iterator.prototype.map()` | `Array.prototype.map()` |
| `Iterator.prototype.reduce()` | `Array.prototype.reduce()` |
| `Iterator.prototype.some()` | `Array.prototype.some()` |

`Iterator.prototype.drop()` and `Iterator.prototype.take()` combined are somewhat analogous to `Array.prototype.slice()`.

Among these methods, `filter()`, `flatMap()`, `map()`, `drop()`, and `take()` return a new *Iterator Helper* object. The iterator helper is also an `Iterator` instance, making the helper methods chainable. All iterator helper objects inherit from a common prototype object, which implements the iterator protocol:

`next()`

Calls the `next()` method of the underlying iterator, applies the helper method to the result, and returns the result.

`return()`

Calls the `return()` method of the underlying iterator, and returns the result.

The iterator helper shares the same data source as the underlying iterator, so iterating the iterator helper causes the underlying iterator to be iterated as well. There is no way to "fork" an iterator to allow it to be iterated multiple times.

```js
const it = [1, 2, 3].values();
const it2 = it.drop(0); // Essentially a copy
console.log(it.next().value); // 1
console.log(it2.next().value); // 2
console.log(it.next().value); // 3
```

### Proper iterators

There are two kinds of "iterators": objects that conform to the iterator protocol (which, at its minimum, only requires the presence of a `next()` method), and objects that inherit from the `Iterator` class, which enjoy the helper methods. They do not entail each other — objects that inherit from `Iterator` do not automatically become iterators, because the `Iterator` class does not define a `next()` method. Instead, the object needs to define a `next()` method itself. A *proper iterator* is one that both conforms to the iterator protocol and inherits from `Iterator`, and most code expect iterators to be proper iterators and iterables to return proper iterators. To create proper iterators, define a class that extends `Iterator`, or use the `Iterator.from()` method.

```js
class MyIterator extends Iterator {
  next() {
    // …
  }
}

const myIterator = Iterator.from({
  next() {
    // …
  },
});
```

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

`Iterator()`
Experimental

Intended to be extended by other classes that create iterators. Throws an error when constructed by itself.

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

`Iterator.from()`
Experimental

Creates a new `Iterator` object from an iterator or iterable object.

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

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

`Iterator.prototype.constructor`

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

`Iterator.prototype[@@toStringTag]`

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

**Note:** Unlike the `@@toStringTag` on most built-in classes, `Iterator.prototype[@@toStringTag]` is writable for web compatibility reasons.

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

`Iterator.prototype.drop()`
Experimental

Returns a new iterator helper that skips the given number of elements at the start of this iterator.

`Iterator.prototype.every()`
Experimental

Tests whether all elements produced by the iterator pass the test implemented by the provided function.

`Iterator.prototype.filter()`
Experimental

Returns a new iterator helper that yields only those elements of the iterator for which the provided callback function returns `true`.

`Iterator.prototype.find()`
Experimental

Returns the first element produced by the iterator that satisfies the provided testing function. If no values satisfy the testing function, `undefined` is returned.

`Iterator.prototype.flatMap()`
Experimental

Returns a new iterator helper that takes each element in the original iterator, runs it through a mapping function, and yields elements returned by the mapping function (which are contained in another iterator or iterable).

`Iterator.prototype.forEach()`
Experimental

Executes a provided function once for each element produced by the iterator.

`Iterator.prototype.map()`
Experimental

Returns a new iterator helper that yields elements of the iterator, each transformed by a mapping function.

`Iterator.prototype.reduce()`
Experimental

Executes a user-supplied "reducer" callback function on each element produced by the iterator, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements is a single value.

`Iterator.prototype.some()`
Experimental

Tests whether at least one element in the iterator passes the test implemented by the provided function. It returns a boolean value.

`Iterator.prototype.take()`
Experimental

Returns a new iterator helper that yields the given number of elements in this iterator and then terminates.

`Iterator.prototype.toArray()`
Experimental

Creates a new `Array` instance populated with the elements yielded from the iterator.

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

Returns the iterator object itself. This allows iterator objects to also be iterable.

Examples
--------

### Using an iterator as an iterable

All built-in iterators are also iterable, so you can use them in a `for...of` loop:

```js
const arrIterator = [1, 2, 3].values();
for (const value of arrIterator) {
  console.log(value);
}
// Logs: 1, 2, 3
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%iteratorprototype%-object |

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

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

See also
--------

* Polyfill of `Iterator` in `core-js`
* `function*`
* Iteration protocols


URIError - JavaScript

URIError
========

The **`URIError`** object represents an error when a global URI handling function was used in a wrong way.

`URIError` is a serializable object, so it can be cloned with `structuredClone()` or copied between Workers using `postMessage()`.

`URIError` is a subclass of `Error`.

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

`URIError()`

Creates a new `URIError` object.

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

*Also inherits instance properties from its parent `Error`*.

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

`URIError.prototype.constructor`

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

`URIError.prototype.name`

Represents the name for the type of error. For `URIError.prototype.name`, the initial value is `"URIError"`.

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

*Inherits instance methods from its parent `Error`*.

Examples
--------

### Catching an URIError

```js
try {
  decodeURIComponent("%");
} catch (e) {
  console.log(e instanceof URIError); // true
  console.log(e.message); // "malformed URI sequence"
  console.log(e.name); // "URIError"
  console.log(e.stack); // Stack of the error
}
```

### Creating an URIError

```js
try {
  throw new URIError("Hello");
} catch (e) {
  console.log(e instanceof URIError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "URIError"
  console.log(e.stack); // Stack of the error
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-native-error-types-used-in-this-standard-urierror |

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

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

See also
--------

* `Error`
* `decodeURI()`
* `decodeURIComponent()`
* `encodeURI()`
* `encodeURIComponent()`


Int16Array - JavaScript

Int16Array
==========

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

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

`Int16Array()`

Creates a new `Int16Array` object.

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

*Also inherits static properties from its parent `TypedArray`*.

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

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

*Also inherits instance properties from its parent `TypedArray`*.

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

`Int16Array.prototype.BYTES_PER_ELEMENT`

Returns a number value of the element size. `2` in the case of a `Int16Array`.

`Int16Array.prototype.constructor`

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

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

*Inherits instance methods from its parent `TypedArray`*.

Examples
--------

### Different ways to create an Int16Array

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

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

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

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

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

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

| Specification |
| --- |
| ECMAScript Language Specification # table-49 |

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

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

See also
--------

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


NaN - JavaScript

NaN
===

The **`NaN`** global property is a value representing Not-A-Number.

Try it
------

Value
-----

The same number value as `Number.NaN`.

| Property attributes of `NaN` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

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

`NaN` is a property of the *global object*. In other words, it is a variable in global scope.

In modern browsers, `NaN` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it.

There are five different types of operations that return `NaN`:

* Failed number conversion (e.g. explicit ones like `parseInt("blabla")`, `Number(undefined)`, or implicit ones like `Math.abs(undefined)`)
* Math operation where the result is not a real number (e.g. `Math.sqrt(-1)`)
* Indeterminate form (e.g. `0 * Infinity`, `1 ** Infinity`, `Infinity / Infinity`, `Infinity - Infinity`)
* A method or expression whose operand is or gets coerced to `NaN` (e.g. `7 ** NaN`, `7 * "blabla"`) — this means `NaN` is contagious
* Other cases where an invalid value is to be represented as a number (e.g. an invalid Date `new Date("blabla").getTime()`, `"".charCodeAt(1)`)

`NaN` and its behaviors are not invented by JavaScript. Its semantics in floating point arithmetic (including that `NaN !== NaN`) are specified by IEEE 754. `NaN`'s behaviors include:

* If `NaN` is involved in a mathematical operation (but not bitwise operations), the result is usually also `NaN`. (See counter-example below.)
* When `NaN` is one of the operands of any relational comparison (`>`, `<`, `>=`, `<=`), the result is always `false`.
* `NaN` compares unequal (via `==`, `!=`, `===`, and `!==`) to any other value — including to another `NaN` value.

`NaN` is also one of the falsy values in JavaScript.

Examples
--------

### Testing against NaN

To tell if a value is `NaN`, use `Number.isNaN()` or `isNaN()` to most clearly determine whether a value is `NaN` — or, since `NaN` is the only value that compares unequal to itself, you can perform a self-comparison like `x !== x`.

```js
NaN === NaN; // false
Number.NaN === NaN; // false
isNaN(NaN); // true
isNaN(Number.NaN); // true
Number.isNaN(NaN); // true

function valueIsNaN(v) {
  return v !== v;
}
valueIsNaN(1); // false
valueIsNaN(NaN); // true
valueIsNaN(Number.NaN); // true
```

However, do note the difference between `isNaN()` and `Number.isNaN()`: the former will return `true` if the value is currently `NaN`, or if it is going to be `NaN` after it is coerced to a number, while the latter will return `true` only if the value is currently `NaN`:

```js
isNaN("hello world"); // true
Number.isNaN("hello world"); // false
```

For the same reason, using a BigInt value will throw an error with `isNaN()` and not with `Number.isNaN()`:

```js
isNaN(1n); // TypeError: Conversion from 'BigInt' to 'number' is not allowed.
Number.isNaN(1n); // false
```

Additionally, some array methods cannot find `NaN`, while others can. Namely, the index-finding ones (`indexOf()`, `lastIndexOf()`) cannot find `NaN`, while the value-finding ones (`includes()`) can:

```js
const arr = [2, 4, NaN, 12];
arr.indexOf(NaN); // -1
arr.includes(NaN); // true

// Methods accepting a properly defined predicate can always find NaN
arr.findIndex((n) => Number.isNaN(n)); // 2
```

For more information about `NaN` and its comparison, see Equality comparison and sameness.

### Observably distinct NaN values

There's a motivation for `NaN` being unequal to itself. It's possible to produce two floating point numbers with different binary representations but are both `NaN`, because in IEEE 754 encoding, any floating point number with exponent `0x7ff` and a non-zero mantissa is `NaN`. In JavaScript, you can do bit-level manipulation using typed arrays.

```js
const f2b = (x) => new Uint8Array(new Float64Array([x]).buffer);
const b2f = (x) => new Float64Array(x.buffer)[0];
// Get a byte representation of NaN
const n = f2b(NaN);
const m = f2b(NaN);
// Change the sign bit, which doesn't matter for NaN
n[7] += 2 \*\* 7;
// n[0] += 2\*\*7; for big endian processors
const nan2 = b2f(n);
console.log(nan2); // NaN
console.log(Object.is(nan2, NaN)); // true
console.log(f2b(NaN)); // Uint8Array(8) [0, 0, 0, 0, 0, 0, 248, 127]
console.log(f2b(nan2)); // Uint8Array(8) [0, 0, 0, 0, 0, 0, 248, 255]
// Change the first bit, which is the least significant bit of the mantissa and doesn't matter for NaN
m[0] = 1;
// m[7] = 1; for big endian processors
const nan3 = b2f(m);
console.log(nan3); // NaN
console.log(Object.is(nan3, NaN)); // true
console.log(f2b(NaN)); // Uint8Array(8) [0, 0, 0, 0, 0, 0, 248, 127]
console.log(f2b(nan3)); // Uint8Array(8) [1, 0, 0, 0, 0, 0, 248, 127]
```

### Silently escaping NaN

`NaN` propagates through mathematical operations, so it's usually sufficient to test for `NaN` once at the end of calculation to detect error conditions. The only case where `NaN` gets silently escaped is when using exponentiation with an exponent of `0`, which immediately returns `1` without testing the base's value.

```js
NaN \*\* 0 === 1; // true
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-value-properties-of-the-global-object-nan |

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

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

See also
--------

* `Number.NaN`
* `Number.isNaN()`
* `isNaN()`


parseInt() - JavaScript

parseInt()
==========

The **`parseInt()`** function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

Try it
------

Syntax
------

```js
parseInt(string)
parseInt(string, radix)
```

### Parameters

`string`

A string starting with an integer. Leading whitespace in this argument is ignored.

`radix` Optional

An integer between `2` and `36` that represents the *radix* (the base in mathematical numeral systems) of the `string`. It is converted to a 32-bit integer; if it's nonzero and outside the range of [2, 36] after conversion, the function will always return `NaN`. If `0` or not provided, the radix will be inferred based on `string`'s value. Be careful — this does *not* always default to `10`! The description below explains in more detail what happens when `radix` is not provided.

### Return value

An integer parsed from the given `string`, or `NaN` when

* the `radix` as a 32-bit integer is smaller than `2` or bigger than `36`, or
* 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()` 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 `Number` 42.

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

The `parseInt` function converts its first argument to a string, parses that string, then returns an integer or `NaN`.

If not `NaN`, the return value will be the integer that is the first argument taken as a number in the specified `radix`. (For example, a `radix` of `10` converts from a decimal number, `8` converts from octal, `16` from hexadecimal, and so on.)

The `radix` argument is converted to a number. If it's unprovided, or if the value becomes 0, `NaN` or `Infinity` (`undefined` is coerced to `NaN`), JavaScript assumes the following:

1. If the input `string`, with leading whitespace and possible `+`/`-` signs removed, begins with `0x` or `0X` (a zero, followed by lowercase or uppercase X), `radix` is assumed to be `16` and the rest of the string is parsed as a hexadecimal number.
2. If the input `string` begins with any other value, the radix is `10` (decimal).

**Note:** Other prefixes like `0b`, which are valid in number literals, are treated as normal digits by `parseInt()`. `parseInt()` does *not* treat strings beginning with a `0` character as octal values either. The only prefix that `parseInt()` recognizes is `0x` or `0X` for hexadecimal values — everything else is parsed as a decimal value if `radix` is missing. `Number()` or `BigInt()` can be used instead to parse these prefixes.

If the radix is `16`, `parseInt()` allows the string to be optionally prefixed by `0x` or `0X` after the optional sign character (`+`/`-`).

If the radix value (coerced if necessary) is not in range [2, 36] (inclusive) `parseInt` returns `NaN`.

For radices above `10`, letters of the English alphabet indicate numerals greater than `9`. For example, for hexadecimal numbers (base `16`), `A` through `F` are used. The letters are case-insensitive.

`parseInt` understands exactly two signs: `+` for positive, and `-` for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string.

If `parseInt` encounters a character that is not a numeral in the specified `radix`, it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although `1e3` technically encodes an integer (and will be correctly parsed to the integer `1000` by `parseFloat()`), `parseInt("1e3", 10)` returns `1`, because `e` is not a valid numeral in base 10. Because `.` is not a numeral either, the return value will always be an integer.

If the first character cannot be converted to a number with the radix in use, `parseInt` returns `NaN`. Leading whitespace is allowed.

For arithmetic purposes, the `NaN` value is not a number in any radix. You can call the `Number.isNaN` function to determine if the result of `parseInt` is `NaN`. If `NaN` is passed on to arithmetic operations, the operation result will also be `NaN`.

Because large numbers use the `e` character in their string representation (e.g. `6.022e23` for 6.022 × 1023), using `parseInt` to truncate numbers will produce unexpected results when used on very large or very small numbers. `parseInt` should *not* be used as a substitute for `Math.trunc()`.

To convert a number to its string literal in a particular radix, use `thatNumber.toString(radix)`.

Because `parseInt()` returns a number, it may suffer from loss of precision if the integer represented by the string is outside the safe range. The `BigInt()` function supports parsing integers of arbitrary length accurately, by returning a `BigInt`.

Examples
--------

### Using parseInt()

The following examples all return `15`:

```js
parseInt("0xF", 16);
parseInt("F", 16);
parseInt("17", 8);
parseInt("015", 10); // but `parseInt('015', 8)` will return 13
parseInt("15,123", 10);
parseInt("FXX123", 16);
parseInt("1111", 2);
parseInt("15 \* 3", 10);
parseInt("15e2", 10);
parseInt("15px", 10);
parseInt("12", 13);
```

The following examples all return `NaN`:

```js
parseInt("Hello", 8); // Not a number at all
parseInt("546", 2); // Digits other than 0 or 1 are invalid for binary radix
```

The following examples all return `-15`:

```js
parseInt("-F", 16);
parseInt("-0F", 16);
parseInt("-0XF", 16);
parseInt("-17", 8);
parseInt("-15", 10);
parseInt("-1111", 2);
parseInt("-15e1", 10);
parseInt("-12", 13);
```

The following example returns `224`:

```js
parseInt("0e0", 16);
```

`parseInt()` does not handle `BigInt` values. It stops at the `n` character, and treats the preceding string as a normal integer, with possible loss of precision.

```js
parseInt("900719925474099267n");
// 900719925474099300
```

You should pass the string to the `BigInt()` function instead, without the trailing `n` character.

```js
BigInt("900719925474099267");
// 900719925474099267n
```

`parseInt` doesn't work with numeric separators:

```js
parseInt("123\_456"); // 123
```

### Using parseInt() on non-strings

`parseInt()` can have interesting results when working on non-strings combined with a high radix; for example, `36` (which makes all alphanumeric characters valid numeric digits).

```js
parseInt(null, 36); // 1112745: The string "null" is 1112745 in base 36
parseInt(undefined, 36); // 86464843759093: The string "undefined" is 86464843759093 in base 36
```

In general, it's a bad idea to use `parseInt()` on non-strings, especially to use it as a substitution for `Math.trunc()`. It may work on small numbers:

```js
parseInt(15.99, 10); // 15
parseInt(-15.1, 10); // -15
```

However, it only happens to work because the string representation of these numbers uses basic fractional notation (`"15.99"`, `"-15.1"`), where `parseInt()` stops at the decimal point. Numbers greater than or equal to 1e+21 or less than or equal to 1e-7 use exponential notation (`"1.5e+22"`, `"1.51e-8"`) in their string representation, and `parseInt()` will stop at the `e` character or decimal point, which always comes after the first digit. This means for large and small numbers, `parseInt()` will return a one-digit integer:

```js
parseInt(4.7 \* 1e22, 10); // Very large number becomes 4
parseInt(0.00000000000434, 10); // Very small number becomes 4

parseInt(0.0000001, 10); // 1
parseInt(0.000000123, 10); // 1
parseInt(1e-7, 10); // 1
parseInt(1000000000000000000000, 10); // 1
parseInt(123000000000000000000000, 10); // 1
parseInt(1e21, 10); // 1
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-parseint-string-radix |

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

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

See also
--------

* `parseFloat()`
* `Number()` constructor
* `Number.parseFloat()`
* `Number.parseInt()`
* `isNaN()`
* `Number.prototype.toString()`
* `Object.prototype.valueOf()`
* `BigInt()` constructor


Infinity - JavaScript

Infinity
========

The **`Infinity`** global property is a numeric value representing infinity.

Try it
------

Value
-----

The same number value as `Number.POSITIVE_INFINITY`.

| Property attributes of `Infinity` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

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

`Infinity` is a property of the *global object*. In other words, it is a variable in global scope.

The value `Infinity` (positive infinity) is greater than any other number.

This value behaves slightly differently than mathematical infinity; see `Number.POSITIVE_INFINITY` for details.

Examples
--------

### Using Infinity

```js
console.log(Infinity); /\* Infinity \*/
console.log(Infinity + 1); /\* Infinity \*/
console.log(Math.pow(10, 1000)); /\* Infinity \*/
console.log(Math.log(0)); /\* -Infinity \*/
console.log(1 / Infinity); /\* 0 \*/
console.log(1 / 0); /\* Infinity \*/
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-value-properties-of-the-global-object-infinity |

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

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

See also
--------

* `Number.NEGATIVE_INFINITY`
* `Number.POSITIVE_INFINITY`
* `Number.isFinite`


Generator - JavaScript

Generator
=========

The **`Generator`** object is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol.

`Generator` is a subclass of the hidden `Iterator` class.

Try it
------

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

The `Generator` constructor is not available globally. Instances of `Generator` must be returned from generator functions:

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

const gen = generator(); // "Generator { }"

console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
```

In fact, there's no JavaScript entity that corresponds to the `Generator` constructor. There's only a hidden object which is the prototype object shared by all objects created by generator functions. This object is often stylized as `Generator.prototype` to make it look like a class, but it should be more appropriately called `GeneratorFunction.prototype.prototype`, because `GeneratorFunction` is an actual JavaScript entity.

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

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

`Generator.prototype.constructor`

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

**Note:** `Generator` objects do not store a reference to the generator function that created them.

`Generator.prototype[@@toStringTag]`

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

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

*Also inherits instance methods from its parent `Iterator`*.

`Generator.prototype.next()`

Returns a value yielded by the `yield` expression.

`Generator.prototype.return()`

Acts as if a `return` statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a `try...finally` block.

`Generator.prototype.throw()`

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

Examples
--------

### An infinite iterator

With a generator function, values are not evaluated until they are needed. Therefore a generator allows us to define a potentially infinite data structure.

```js
function\* infinite() {
  let index = 0;

  while (true) {
    yield index++;
  }
}

const generator = infinite(); // "Generator { }"

console.log(generator.next().value); // 0
console.log(generator.next().value); // 1
console.log(generator.next().value); // 2
// …
```

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

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

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

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

See also
--------

* `function*`
* `function*` expression
* `GeneratorFunction`
* Iteration protocols


AsyncGenerator - JavaScript

AsyncGenerator
==============

The **`AsyncGenerator`** object is returned by an async generator function and it conforms to both the async iterable protocol and the async iterator protocol.

Async generator methods always yield `Promise` objects.

`AsyncGenerator` is a subclass of the hidden `AsyncIterator` class.

Try it
------

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

The `AsyncGenerator` constructor is not available globally. Instances of `AsyncGenerator` must be returned from async generator functions

```js
async function\* createAsyncGenerator() {
  yield await Promise.resolve(1);
  yield await Promise.resolve(2);
  yield await Promise.resolve(3);
}
const asyncGen = createAsyncGenerator();
asyncGen.next().then((res) => console.log(res.value)); // 1
asyncGen.next().then((res) => console.log(res.value)); // 2
asyncGen.next().then((res) => console.log(res.value)); // 3
```

In fact, there's no JavaScript entity that corresponds to the `AsyncGenerator` constructor. There's only a hidden object which is the prototype object shared by all objects created by async generator functions. This object is often stylized as `AsyncGenerator.prototype` to make it look like a class, but it should be more appropriately called `AsyncGeneratorFunction.prototype.prototype`, because `AsyncGeneratorFunction` is an actual JavaScript entity.

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

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

`AsyncGenerator.prototype.constructor`

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

**Note:** `AsyncGenerator` objects do not store a reference to the async generator function that created them.

`AsyncGenerator.prototype[@@toStringTag]`

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

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

*Also inherits instance methods from its parent `AsyncIterator`*.

`AsyncGenerator.prototype.next()`

Returns a `Promise` which will be resolved with the given value yielded by the `yield` expression.

`AsyncGenerator.prototype.return()`

Acts as if a `return` statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a `try...finally` block.

`AsyncGenerator.prototype.throw()`

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

Examples
--------

### Async generator iteration

The following example iterates over an async generator, logging values 1–6 to the console at decreasing time intervals. Notice how each time a Promise is yielded, but it's automatically resolved within the `for await...of` loop.

```js
// An async task. Pretend it's doing something more useful
// in practice.
function delayedValue(time, value) {
  return new Promise((resolve /\*, reject\*/) => {
    setTimeout(() => resolve(value), time);
  });
}

async function\* generate() {
  yield delayedValue(2000, 1);
  yield delayedValue(100, 2);
  yield delayedValue(500, 3);
  yield delayedValue(250, 4);
  yield delayedValue(125, 5);
  yield delayedValue(50, 6);
  console.log("All done!");
}

async function main() {
  for await (const value of generate()) {
    console.log("value", value);
  }
}

main().catch((e) => console.error(e));
```

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

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

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

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

See also
--------

* function\*
* async function\*
* `function*` expression
* Generator Function
* Async Generator Function
* Iterators and generators guide


WeakRef - JavaScript

WeakRef
=======

A **`WeakRef`** object lets you hold a weak reference to another object, without preventing that object from getting garbage-collected.

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

A `WeakRef` object contains a weak reference to an object, which is called its *target* or *referent*. A *weak reference* to an object is a reference that does not prevent the object from being reclaimed by the garbage collector. In contrast, a normal (or *strong*) reference keeps an object in memory. When an object no longer has any strong references to it, the JavaScript engine's garbage collector may destroy the object and reclaim its memory. If that happens, you can't get the object from a weak reference anymore.

Because non-registered symbols are also garbage collectable, they can also be used as the target of a `WeakRef` object. However, the use case of this is limited.

### Avoid where possible

Correct use of `WeakRef` takes careful thought, and it's best avoided if possible. It's also important to avoid relying on any specific behaviors not guaranteed by the specification. When, how, and whether garbage collection occurs is down to the implementation of any given JavaScript engine. Any behavior you observe in one engine may be different in another engine, in another version of the same engine, or even in a slightly different situation with the same version of the same engine. Garbage collection is a hard problem that JavaScript engine implementers are constantly refining and improving their solutions to.

Here are some specific points included by the authors in the proposal that introduced `WeakRef`:

>
> Garbage collectors are complicated. If an application or library depends on GC cleaning up a WeakRef or calling a finalizer [cleanup callback] in a timely, predictable manner, it's likely to be disappointed: the cleanup may happen much later than expected, or not at all. Sources of variability include:
>
>
> * One object might be garbage-collected much sooner than another object, even if they become unreachable at the same time, e.g., due to generational collection.
> * Garbage collection work can be split up over time using incremental and concurrent techniques.
> * Various runtime heuristics can be used to balance memory usage, responsiveness.
> * The JavaScript engine may hold references to things which look like they are unreachable (e.g., in closures, or inline caches).
> * Different JavaScript engines may do these things differently, or the same engine may change its algorithms across versions.
> * Complex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain APIs.
>
>
>

### Notes on WeakRefs

* If your code has just created a `WeakRef` for a target object, or has gotten a target object from a `WeakRef`'s `deref` method, that target object will not be reclaimed until the end of the current JavaScript job (including any promise reaction jobs that run at the end of a script job). That is, you can only "see" an object get reclaimed between turns of the event loop. This is primarily to avoid making the behavior of any given JavaScript engine's garbage collector apparent in code — because if it were, people would write code relying on that behavior, which would break when the garbage collector's behavior changed. (Garbage collection is a hard problem; JavaScript engine implementers are constantly refining and improving how it works.)
* If multiple `WeakRef`s have the same target, they're consistent with one another. The result of calling `deref` on one of them will match the result of calling `deref` on another of them (in the same job), you won't get the target object from one of them but `undefined` from another.
* If the target of a `WeakRef` is also in a `FinalizationRegistry`, the `WeakRef`'s target is cleared at the same time or before any cleanup callback associated with the registry is called; if your cleanup callback calls `deref` on a `WeakRef` for the object, it will receive `undefined`.
* You cannot change the target of a `WeakRef`, it will always only ever be the original target object or `undefined` when that target has been reclaimed.
* A `WeakRef` might never return `undefined` from `deref`, even if nothing strongly holds the target, because the garbage collector may never decide to reclaim the object.
Constructor
-----------

`WeakRef()`

Creates a new `WeakRef` object.

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

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

`WeakRef.prototype.constructor` Optional

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

**Note:** This property is marked as "normative optional" in the specification, which means a conforming implementation may not expose the `constructor` property. This prevents arbitrary code from obtaining the `WeakRef` constructor and being able to observe garbage collection. However, all major engines do expose it by default.

`WeakRef.prototype[@@toStringTag]`

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

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

`WeakRef.prototype.deref()`

Returns the `WeakRef` object's target object, or `undefined` if the target object has been reclaimed.

Examples
--------

### Using a WeakRef object

This example starts a counter shown in a DOM element, stopping when the element doesn't exist anymore:

```js
class Counter {
  constructor(element) {
    // Remember a weak reference to the DOM element
    this.ref = new WeakRef(element);
    this.start();
  }

  start() {
    if (this.timer) {
      return;
    }

    this.count = 0;

    const tick = () => {
      // Get the element from the weak reference, if it still exists
      const element = this.ref.deref();
      if (element) {
        element.textContent = ++this.count;
      } else {
        // The element doesn't exist anymore
        console.log("The element is gone.");
        this.stop();
        this.ref = null;
      }
    };

    tick();
    this.timer = setInterval(tick, 1000);
  }

  stop() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = 0;
    }
  }
}

const counter = new Counter(document.getElementById("counter"));
setTimeout(() => {
  document.getElementById("counter").remove();
}, 5000);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-weak-ref-objects |

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

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

See also
--------

* `FinalizationRegistry`
* `WeakSet`
* `WeakMap`


Object - JavaScript

Object
======

The **`Object`** type represents one of JavaScript's data types. It is used to store various keyed collections and more complex entities. Objects can be created using the `Object()` constructor or the object initializer / literal syntax.

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

Nearly all objects in JavaScript are instances of `Object`; a typical object inherits properties (including methods) from `Object.prototype`, although these properties may be shadowed (a.k.a. overridden). The only objects that don't inherit from `Object.prototype` are those with `null` prototype, or descended from other `null` prototype objects.

Changes to the `Object.prototype` object are seen by **all** objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain. This provides a very powerful although potentially dangerous mechanism to override or extend object behavior. To make it more secure, `Object.prototype` is the only object in the core JavaScript language that has immutable prototype — the prototype of `Object.prototype` is always `null` and not changeable.

### Object prototype properties

You should avoid calling any `Object.prototype` method directly from the instance, especially those that are not intended to be polymorphic (i.e. only its initial behavior makes sense and no descending object could override it in a meaningful way). All objects descending from `Object.prototype` may define a custom own property that has the same name, but with entirely different semantics from what you expect. Furthermore, these properties are not inherited by `null`-prototype objects. All modern JavaScript utilities for working with objects are static. More specifically:

* `valueOf()`, `toString()`, and `toLocaleString()` exist to be polymorphic and you should expect the object to define its own implementation with sensible behaviors, so you can call them as instance methods. However, `valueOf()` and `toString()` are usually implicitly called through type conversion and you don't need to call them yourself in your code.
* `__defineGetter__()`, `__defineSetter__()`, `__lookupGetter__()`, and `__lookupSetter__()` are deprecated and should not be used. Use the static alternatives `Object.defineProperty()` and `Object.getOwnPropertyDescriptor()` instead.
* The `__proto__` property is deprecated and should not be used. The `Object.getPrototypeOf()` and `Object.setPrototypeOf()` alternatives are static methods.
* The `propertyIsEnumerable()` and `hasOwnProperty()` methods can be replaced with the `Object.getOwnPropertyDescriptor()` and `Object.hasOwn()` static methods, respectively.
* The `isPrototypeOf()` method can usually be replaced with `instanceof`, if you are checking the `prototype` property of a constructor.

In case where a semantically equivalent static method doesn't exist, or if you really want to use the `Object.prototype` method, you should directly `call()` the `Object.prototype` method on your target object instead, to prevent the object from having an overriding property that produces unexpected results.

```js
const obj = {
  foo: 1,
  // You should not define such a method on your own object,
  // but you may not be able to prevent it from happening if
  // you are receiving the object from external input
  propertyIsEnumerable() {
    return false;
  },
};

obj.propertyIsEnumerable("foo"); // false; unexpected result
Object.prototype.propertyIsEnumerable.call(obj, "foo"); // true; expected result
```

### Deleting a property from an object

There isn't any method in an Object itself to delete its own properties (such as `Map.prototype.delete()`). To do so, one must use the `delete` operator.

### null-prototype objects

Almost all objects in JavaScript ultimately inherit from `Object.prototype` (see inheritance and the prototype chain). However, you may create `null`-prototype objects using `Object.create(null)` or the object initializer syntax with `__proto__: null` (note: the `__proto__` key in object literals is different from the deprecated `Object.prototype.__proto__` property). You can also change the prototype of an existing object to `null` by calling `Object.setPrototypeOf(obj, null)`.

```js
const obj = Object.create(null);
const obj2 = { \_\_proto\_\_: null };
```

An object with a `null` prototype can behave in unexpected ways, because it doesn't inherit any object methods from `Object.prototype`. This is especially true when debugging, since common object-property converting/detecting utility functions may generate errors, or lose information (especially if using silent error-traps that ignore errors).

For example, the lack of `Object.prototype.toString()` often makes debugging intractable:

```js
const normalObj = {}; // create a normal object
const nullProtoObj = Object.create(null); // create an object with "null" prototype

console.log(`normalObj is: ${normalObj}`); // shows "normalObj is: [object Object]"
console.log(`nullProtoObj is: ${nullProtoObj}`); // throws error: Cannot convert object to primitive value

alert(normalObj); // shows [object Object]
alert(nullProtoObj); // throws error: Cannot convert object to primitive value
```

Other methods will fail as well.

```js
normalObj.valueOf(); // shows {}
nullProtoObj.valueOf(); // throws error: nullProtoObj.valueOf is not a function

normalObj.hasOwnProperty("p"); // shows "true"
nullProtoObj.hasOwnProperty("p"); // throws error: nullProtoObj.hasOwnProperty is not a function

normalObj.constructor; // shows "Object() { [native code] }"
nullProtoObj.constructor; // shows "undefined"
```

We can add the `toString` method back to the null-prototype object by assigning it one:

```js
nullProtoObj.toString = Object.prototype.toString; // since new object lacks toString, add the original generic one back

console.log(nullProtoObj.toString()); // shows "[object Object]"
console.log(`nullProtoObj is: ${nullProtoObj}`); // shows "nullProtoObj is: [object Object]"
```

Unlike normal objects, in which `toString()` is on the object's prototype, the `toString()` method here is an own property of `nullProtoObj`. This is because `nullProtoObj` has no (`null`) prototype.

You can also revert a null-prototype object back to an ordinary object using `Object.setPrototypeOf(nullProtoObj, Object.prototype)`.

In practice, objects with `null` prototype are usually used as a cheap substitute for maps. The presence of `Object.prototype` properties will cause some bugs:

```js
const ages = { alice: 18, bob: 27 };

function hasPerson(name) {
  return name in ages;
}

function getAge(name) {
  return ages[name];
}

hasPerson("hasOwnProperty"); // true
getAge("toString"); // [Function: toString]
```

Using a null-prototype object removes this hazard without introducing too much complexity to the `hasPerson` and `getAge` functions:

```js
const ages = Object.create(null, {
  alice: { value: 18, enumerable: true },
  bob: { value: 27, enumerable: true },
});

hasPerson("hasOwnProperty"); // false
getAge("toString"); // undefined
```

In such case, the addition of any method should be done cautiously, as they can be confused with the other key-value pairs stored as data.

Making your object not inherit from `Object.prototype` also prevents prototype pollution attacks. If a malicious script adds a property to `Object.prototype`, it will be accessible on every object in your program, except objects that have null prototype.

```js
const user = {};

// A malicious script:
Object.prototype.authenticated = true;

// Unexpectedly allowing unauthenticated user to pass through
if (user.authenticated) {
  // access confidential data
}
```

JavaScript also has built-in APIs that produce `null`-prototype objects, especially those that use objects as ad hoc key-value collections. For example:

* The return value of `Object.groupBy()`
* The `groups` and `indices.groups` properties of the result of `RegExp.prototype.exec()`
* `Array.prototype[@@unscopables]` (all `@@unscopables` objects should have `null`-prototype)
* `import.meta`
* Module namespace objects, obtained through `import * as ns from "module";` or `import()`

The term "`null`-prototype object" often also includes any object without `Object.prototype` in its prototype chain. Such objects can be created with `extends null` when using classes.

### Object coercion

Many built-in operations that expect objects first coerce their arguments to objects. The operation can be summarized as follows:

* Objects are returned as-is.
* `undefined` and `null` throw a `TypeError`.
* `Number`, `String`, `Boolean`, `Symbol`, `BigInt` primitives are wrapped into their corresponding object wrappers.

There are two ways to achieve nearly the same effect in JavaScript.

* `Object.prototype.valueOf()`: `Object.prototype.valueOf.call(x)` does exactly the object coercion steps explained above to convert `x`.
* The `Object()` function: `Object(x)` uses the same algorithm to convert `x`, except that `undefined` and `null` don't throw a `TypeError`, but return a plain object.

Places that use object coercion include:

* The `object` parameter of `for...in` loops.
* The `this` value of `Array` methods.
* Parameters of `Object` methods such as `Object.keys()`.
* Auto-boxing when a property is accessed on a primitive value, since primitives do not have properties.
* The `this` value when calling a non-strict function. Primitives are boxed while `null` and `undefined` are replaced with the global object.

Unlike conversion to primitives, the object coercion process itself is not observable in any way, since it doesn't invoke custom code like `toString` or `valueOf` methods.

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

`Object()`

Turns the input into an object.

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

`Object.assign()`

Copies the values of all enumerable own properties from one or more source objects to a target object.

`Object.create()`

Creates a new object with the specified prototype object and properties.

`Object.defineProperties()`

Adds the named properties described by the given descriptors to an object.

`Object.defineProperty()`

Adds the named property described by a given descriptor to an object.

`Object.entries()`

Returns an array containing all of the `[key, value]` pairs of a given object's **own** enumerable string properties.

`Object.freeze()`

Freezes an object. Other code cannot delete or change its properties.

`Object.fromEntries()`

Returns a new object from an iterable of `[key, value]` pairs. (This is the reverse of `Object.entries`).

`Object.getOwnPropertyDescriptor()`

Returns a property descriptor for a named property on an object.

`Object.getOwnPropertyDescriptors()`

Returns an object containing all own property descriptors for an object.

`Object.getOwnPropertyNames()`

Returns an array containing the names of all of the given object's **own** enumerable and non-enumerable properties.

`Object.getOwnPropertySymbols()`

Returns an array of all symbol properties found directly upon a given object.

`Object.getPrototypeOf()`

Returns the prototype (internal `[[Prototype]]` property) of the specified object.

`Object.groupBy()`

Groups the elements of a given iterable according to the string values returned by a provided callback function. The returned object has separate properties for each group, containing arrays with the elements in the group.

`Object.hasOwn()`

Returns `true` if the specified object has the indicated property as its *own* property, or `false` if the property is inherited or does not exist.

`Object.is()`

Compares if two values are the same value. Equates all `NaN` values (which differs from both `IsLooselyEqual` used by `==` and `IsStrictlyEqual` used by `===`).

`Object.isExtensible()`

Determines if extending of an object is allowed.

`Object.isFrozen()`

Determines if an object was frozen.

`Object.isSealed()`

Determines if an object is sealed.

`Object.keys()`

Returns an array containing the names of all of the given object's **own** enumerable string properties.

`Object.preventExtensions()`

Prevents any extensions of an object.

`Object.seal()`

Prevents other code from deleting properties of an object.

`Object.setPrototypeOf()`

Sets the object's prototype (its internal `[[Prototype]]` property).

`Object.values()`

Returns an array containing the values that correspond to all of a given object's **own** enumerable string properties.

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

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

`Object.prototype.__proto__`
Deprecated

Points to the object which was used as prototype when the object was instantiated.

`Object.prototype.constructor`

The constructor function that created the instance object. For plain `Object` instances, the initial value is the `Object` constructor. Instances of other constructors each inherit the `constructor` property from their respective `Constructor.prototype` object.

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

`Object.prototype.__defineGetter__()`
Deprecated

Associates a function with a property that, when accessed, executes that function and returns its return value.

`Object.prototype.__defineSetter__()`
Deprecated

Associates a function with a property that, when set, executes that function which modifies the property.

`Object.prototype.__lookupGetter__()`
Deprecated

Returns the function bound as a getter to the specified property.

`Object.prototype.__lookupSetter__()`
Deprecated

Returns the function bound as a setter to the specified property.

`Object.prototype.hasOwnProperty()`

Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.

`Object.prototype.isPrototypeOf()`

Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.

`Object.prototype.propertyIsEnumerable()`

Returns a boolean indicating whether the specified property is the object's enumerable own property.

`Object.prototype.toLocaleString()`

Calls `toString()`.

`Object.prototype.toString()`

Returns a string representation of the object.

`Object.prototype.valueOf()`

Returns the primitive value of the specified object.

Examples
--------

### Constructing empty objects

The following example creates empty objects using the `new` keyword with different arguments:

```js
const o1 = new Object();
const o2 = new Object(undefined);
const o3 = new Object(null);
```

### Using Object() constructor to turn primitives into an Object of their respective type

You can use the `Object()` constructor to create an object wrapper of a primitive value.

The following examples create variables `o1` and `o2` which are objects storing `Boolean` and `BigInt` values:

```js
// Equivalent to const o1 = new Boolean(true)
const o1 = new Object(true);

// No equivalent because BigInt() can't be called as a constructor,
// and calling it as a regular function won't create an object
const o2 = new Object(1n);
```

### Object prototypes

When altering the behavior of existing `Object.prototype` methods, consider injecting code by wrapping your extension before or after the existing logic. For example, this (untested) code will pre-conditionally execute custom logic before the built-in logic or someone else's extension is executed.

When modifying prototypes with hooks, pass `this` and the arguments (the call state) to the current behavior by calling `apply()` on the function. This pattern can be used for any prototype, such as `Node.prototype`, `Function.prototype`, etc.

```js
const current = Object.prototype.valueOf;

// Since my property "-prop-value" is cross-cutting and isn't always
// on the same prototype chain, I want to modify Object.prototype:
Object.prototype.valueOf = function (...args) {
  if (Object.hasOwn(this, "-prop-value")) {
    return this["-prop-value"];
  } else {
    // It doesn't look like one of my objects, so let's fall back on
    // the default behavior by reproducing the current behavior as best we can.
    // The apply behaves like "super" in some other languages.
    // Even though valueOf() doesn't take arguments, some other hook may.
    return current.apply(this, args);
  }
};
```

**Warning:** Modifying the `prototype` property of any built-in constructor is considered a bad practice and risks forward compatibility.

You can read more about prototypes in Inheritance and the prototype chain.

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

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

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

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

See also
--------

* Object initializer


Int8Array - JavaScript

Int8Array
=========

The **`Int8Array`** typed array represents an array of 8-bit signed integers. 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).

`Int8Array` is a subclass of the hidden `TypedArray` class.

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

`Int8Array()`

Creates a new `Int8Array` object.

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

*Also inherits static properties from its parent `TypedArray`*.

`Int8Array.BYTES_PER_ELEMENT`

Returns a number value of the element size. `1` in the case of `Int8Array`.

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

*Inherits static methods from its parent `TypedArray`*.

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

*Also inherits instance properties from its parent `TypedArray`*.

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

`Int8Array.prototype.BYTES_PER_ELEMENT`

Returns a number value of the element size. `1` in the case of a `Int8Array`.

`Int8Array.prototype.constructor`

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

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

*Inherits instance methods from its parent `TypedArray`*.

Examples
--------

### Different ways to create an Int8Array

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

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

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

// From an ArrayBuffer
const buffer = new ArrayBuffer(8);
const z = new Int8Array(buffer, 1, 4);
console.log(z.byteOffset); // 1

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

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

| Specification |
| --- |
| ECMAScript Language Specification # table-49 |

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

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

See also
--------

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


BigUint64Array - JavaScript

BigUint64Array
==============

The **`BigUint64Array`** typed array represents an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use `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).

`BigUint64Array` is a subclass of the hidden `TypedArray` class.

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

`BigUint64Array()`

Creates a new `BigUint64Array` object.

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

*Also inherits static properties from its parent `TypedArray`*.

`BigUint64Array.BYTES_PER_ELEMENT`

Returns a number value of the element size. `8` in the case of `BigUint64Array`.

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

*Inherits static methods from its parent `TypedArray`*.

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

*Also inherits instance properties from its parent `TypedArray`*.

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

`BigUint64Array.prototype.BYTES_PER_ELEMENT`

Returns a number value of the element size. `8` in the case of a `BigUint64Array`.

`BigUint64Array.prototype.constructor`

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

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

*Inherits instance methods from its parent `TypedArray`*.

Examples
--------

### Different ways to create a BigUint64Array

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

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

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

// From an ArrayBuffer
const buffer = new ArrayBuffer(64);
const z = new BigUint64Array(buffer, 8, 4);
console.log(z.byteOffset); // 8

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

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

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

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

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

See also
--------

* JavaScript typed arrays guide
* `TypedArray`
* `ArrayBuffer`
* `DataView`


AsyncGeneratorFunction - JavaScript

AsyncGeneratorFunction
======================

The **`AsyncGeneratorFunction`** object provides methods for async generator functions. In JavaScript, every async generator function is actually an `AsyncGeneratorFunction` object.

Note that `AsyncGeneratorFunction` is *not* a global object. It can be obtained with the following code:

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

`AsyncGeneratorFunction` is a subclass of `Function`.

Try it
------

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

`AsyncGeneratorFunction()`

Creates a new `AsyncGeneratorFunction` object.

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

*Also inherits instance properties from its parent `Function`*.

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

`AsyncGeneratorFunction.prototype.constructor`

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

`AsyncGeneratorFunction.prototype.prototype`

All async generator functions share the same `prototype` property, which is `AsyncGenerator.prototype`. Each async generator function instance also has its own `prototype` property. When the async generator function is called, the returned async generator object inherits from the async generator function's `prototype` property, which in turn inherits from `AsyncGeneratorFunction.prototype.prototype`.

`AsyncGeneratorFunction.prototype[@@toStringTag]`

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

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

*Inherits instance methods from its parent `Function`*.

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

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

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

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

See also
--------

* `async function*`
* `async function*` expression
* `Function`
* `AsyncFunction`
* `GeneratorFunction`
* Functions


RegExp - JavaScript

RegExp
======

The **`RegExp`** object is used for matching text with a pattern.

For an introduction to regular expressions, read the Regular expressions chapter in the JavaScript guide. For detailed information of regular expression syntax, read the regular expression reference.

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

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.

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

1. `x` must be an object (not a primitive).
2. If `x[Symbol.match]` is not `undefined`, check if it's 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 but not `undefined` (even with everything else intact, like `exec` and `@@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()`, `startsWith()`, and `includes()` throw a `TypeError` if the first argument is a regex.
* `String.prototype.matchAll()` and `replaceAll()` check whether the global flag is set if the first argument is a regex before invoking its `@@matchAll` or `@@replace` method.
* The `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()` 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 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()`), 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 `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.

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

`RegExp()`

Creates a new `RegExp` object.

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

`RegExp.$1, …, RegExp.$9`
Deprecated

Static read-only properties that contain parenthesized substring matches.

`RegExp.input ($_)`
Deprecated

A static property that contains the last string against which a regular expression was successfully matched.

`RegExp.lastMatch ($&)`
Deprecated

A static read-only property that contains the last matched substring.

`RegExp.lastParen ($+)`
Deprecated

A static read-only property that contains the last parenthesized substring match.

`RegExp.leftContext ($`)`
Deprecated

A static read-only property that contains the substring preceding the most recent match.

`RegExp.rightContext ($')`
Deprecated

A static read-only property that contains the substring following the most recent match.

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

`RegExp.prototype.constructor`

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

`RegExp.prototype.dotAll`

Whether `.` matches newlines or not.

`RegExp.prototype.flags`

A string that contains the flags of the `RegExp` object.

`RegExp.prototype.global`

Whether to test the regular expression against all possible matches in a string, or only against the first.

`RegExp.prototype.hasIndices`

Whether the regular expression result exposes the start and end indices of captured substrings.

`RegExp.prototype.ignoreCase`

Whether to ignore case while attempting a match in a string.

`RegExp.prototype.multiline`

Whether or not to search in strings across multiple lines.

`RegExp.prototype.source`

The text of the pattern.

`RegExp.prototype.sticky`

Whether or not the search is sticky.

`RegExp.prototype.unicode`

Whether or not Unicode features are enabled.

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

`lastIndex`

The index at which to start the next match.

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

`RegExp.prototype.compile()`
Deprecated

(Re-)compiles a regular expression during execution of a script.

`RegExp.prototype.exec()`

Executes a search for a match in its string parameter.

`RegExp.prototype.test()`

Tests for a match in its string parameter.

`RegExp.prototype.toString()`

Returns a string representing the specified object. Overrides the `Object.prototype.toString()` method.

`RegExp.prototype[@@match]()`

Performs match to given string and returns match result.

`RegExp.prototype[@@matchAll]()`

Returns all matches of the regular expression against a string.

`RegExp.prototype[@@replace]()`

Replaces matches in given string with new substring.

`RegExp.prototype[@@search]()`

Searches the match in given string and returns the index the pattern found in the string.

`RegExp.prototype[@@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 `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 `sticky` flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at `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 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.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-regexp-regular-expression-objects |

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

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

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

See also
--------

* Polyfill of many modern `RegExp` features (`dotAll`, `sticky` flags, named capture groups, etc.) in `core-js`
* Regular expressions guide
* Regular expressions
* `String.prototype.match()`
* `String.prototype.replace()`
* `String.prototype.split()`