Date - JavaScript

Date
====

JavaScript **`Date`** objects represent a single moment in time in a platform-independent format. `Date` objects encapsulate an integral number that represents milliseconds since the midnight at the beginning of January 1, 1970, UTC (the *epoch*).

**Note:** TC39 is working on Temporal, a new Date/Time API. Read more about it on the Igalia blog. It is not yet ready for production use!

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

### The epoch, timestamps, and invalid date

A JavaScript date is fundamentally specified as the time in milliseconds that has elapsed since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC (equivalent to the UNIX epoch). This timestamp is *timezone-agnostic* and uniquely defines an instant in history.

**Note:** While the time value at the heart of a Date object is UTC, the basic methods to fetch the date and time or its components all work in the local (i.e. host system) time zone and offset.

The maximum timestamp representable by a `Date` object is slightly smaller than the maximum safe integer (`Number.MAX_SAFE_INTEGER`, which is 9,007,199,254,740,991). A `Date` object can represent a maximum of ±8,640,000,000,000,000 milliseconds, or ±100,000,000 (one hundred million) days, relative to the epoch. This is the range from April 20, 271821 BC to September 13, 275760 AD. Any attempt to represent a time outside this range results in the `Date` object holding a timestamp value of `NaN`, which is an "Invalid Date".

```js
console.log(new Date(8.64e15).toString()); // "Sat Sep 13 275760 00:00:00 GMT+0000 (Coordinated Universal Time)"
console.log(new Date(8.64e15 + 1).toString()); // "Invalid Date"
```

There are various methods that allow you to interact with the timestamp stored in the date:

* You can interact with the timestamp value directly using the `getTime()` and `setTime()` methods.
* The `valueOf()` and `[@@toPrimitive]()` (when passed `"number"`) methods — which are automatically called in number coercion — return the timestamp, causing `Date` objects to behave like their timestamps when used in number contexts.
* All static methods (`Date.now()`, `Date.parse()`, and `Date.UTC()`) return timestamps instead of `Date` objects.
* The `Date()` constructor can be called with a timestamp as the only argument.
### Date components and time zones

A date is represented internally as a single number, the *timestamp*. When interacting with it, the timestamp needs to be interpreted as a structured date-and-time representation. There are always two ways to interpret a timestamp: as a local time or as a Coordinated Universal Time (UTC), the global standard time defined by the World Time Standard. The local timezone is not stored in the date object, but is determined by the host environment (user's device).

**Note:** UTC should not be confused with the Greenwich Mean Time (GMT), because they are not always equal — this is explained in more detail in the linked Wikipedia page.

For example, the timestamp 0 represents a unique instant in history, but it can be interpreted in two ways:

* As a UTC time, it is midnight at the beginning of January 1, 1970, UTC,
* As a local time in New York (UTC-5), it is 19:00:00 on December 31, 1969.

The `getTimezoneOffset()` method returns the difference between UTC and the local time in minutes. Note that the timezone offset does not only depend on the current timezone, but also on the time represented by the `Date` object, because of daylight saving time and historical changes. In essence, the timezone offset is the offset from UTC time, at the time represented by the `Date` object and at the location of the host environment.

There are two groups of `Date` methods: one group gets and sets various date components by interpreting the timestamp as a local time, while the other uses UTC.

| Component | Local | UTC |
| --- | --- | --- |
| Get | Set | Get | Set |
| Year | `getFullYear()` | `setFullYear()` | `getUTCFullYear()` | `setUTCFullYear()` |
| Month | `getMonth()` | `setMonth()` | `getUTCMonth()` | `setUTCMonth()` |
| Date (of month) | `getDate()` | `setDate()` | `getUTCDate()` | `setUTCDate()` |
| Hours | `getHours()` | `setHours()` | `getUTCHours()` | `setUTCHours()` |
| Minutes | `getMinutes()` | `setMinutes()` | `getUTCMinutes()` | `setUTCMinutes()` |
| Seconds | `getSeconds()` | `setSeconds()` | `getUTCSeconds()` | `setUTCSeconds()` |
| Milliseconds | `getMilliseconds()` | `setMilliseconds()` | `getUTCMilliseconds()` | `setUTCMilliseconds()` |
| Day (of week) | `getDay()` | N/A | `getUTCDay()` | N/A |

The `Date()` constructor can be called with two or more arguments, in which case they are interpreted as the year, month, day, hour, minute, second, and millisecond, respectively, in local time. `Date.UTC()` works similarly, but it interprets the components as UTC time and also accepts a single argument representing the year.

**Note:** Some methods, including the `Date()` constructor, `Date.UTC()`, and the deprecated `getYear()`/`setYear()` methods, interpret a two-digit year as a year in the 1900s. For example, `new Date(99, 5, 24)` is interpreted as June 24, 1999, not June 24, 99. See Interpretation of two-digit years for more information.

When a segment overflows or underflows its expected range, it usually "carries over to" or "borrows from" the higher segment. For example, if the month is set to 12 (months are zero-based, so December is 11), it become the January of the next year. If the day of month is set to 0, it becomes the last day of the previous month. This also applies to dates specified with the date time string format.

### Date time string format

There are many ways to format a date as a string. The JavaScript specification only specifies one format to be universally supported: the *date time string format*, a simplification of the ISO 8601 calendar date extended format. The format is as follows:
```

YYYY-MM-DDTHH:mm:ss.sssZ
```

* `YYYY` is the year, with four digits (`0000` to `9999`), or as an *expanded year* of `+` or `-` followed by six digits. The sign is required for expanded years. `-000000` is explicitly disallowed as a valid year.
* `MM` is the month, with two digits (`01` to `12`). Defaults to `01`.
* `DD` is the day of the month, with two digits (`01` to `31`). Defaults to `01`.
* `T` is a literal character, which indicates the beginning of the *time* part of the string. The `T` is required when specifying the time part.
* `HH` is the hour, with two digits (`00` to `23`). As a special case, `24:00:00` is allowed, and is interpreted as midnight at the beginning of the next day. Defaults to `00`.
* `mm` is the minute, with two digits (`00` to `59`). Defaults to `00`.
* `ss` is the second, with two digits (`00` to `59`). Defaults to `00`.
* `sss` is the millisecond, with three digits (`000` to `999`). Defaults to `000`.
* `Z` is the timezone offset, which can either be the literal character `Z` (indicating UTC), or `+` or `-` followed by `HH:mm`, the offset in hours and minutes from UTC.

Various components can be omitted, so the following are all valid:

* Date-only form: `YYYY`, `YYYY-MM`, `YYYY-MM-DD`
* Date-time form: one of the above date-only forms, followed by `T`, followed by `HH:mm`, `HH:mm:ss`, or `HH:mm:ss.sss`. Each combination can be followed by a time zone offset.

For example, `"2011-10-10"` (*date-only* form), `"2011-10-10T14:48:00"` (*date-time* form), or `"2011-10-10T14:48:00.000+09:00"` (*date-time* form with milliseconds and time zone) are all valid date time strings.

When the time zone offset is absent, **date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time.** This is due to a historical spec error that was not consistent with ISO 8601 but could not be changed due to web compatibility. See Broken Parser – A Web Reality Issue.

`Date.parse()` and the `Date()` constructor both accept strings in the date time string format as input. Furthermore, implementations are allowed to support other date formats when the input fails to match this format.

The `toISOString()` method returns a string representation of the date in the date time string format, with the time zone offset always set to `Z` (UTC).

**Note:** You are encouraged to make sure your input conforms to the date time string format above for maximum compatibility, because support for other formats is not guaranteed. However, there are some formats that are supported in all major implementations — like RFC 2822 format — in which case their usage can be acceptable. Always conduct cross-browser tests to ensure your code works in all target browsers. A library can help if many different formats are to be accommodated.

Non-standard strings can be parsed in any way as desired by the implementation, including the time zone — most implementations use the local time zone by default. Implementations are not required to return invalid date for out-of-bounds date components, although they usually do. A string may have in-bounds date components (with the bounds defined above), but does not represent a date in reality (for example, "February 30"). Implementations behave inconsistently in this case. The `Date.parse()` page offers more examples about these non-standard cases.

### Other ways to format a date

* `toISOString()` returns a string in the format `1970-01-01T00:00:00.000Z` (the date time string format introduced above, which is simplified ISO 8601). `toJSON()` calls `toISOString()` and returns the result.
* `toString()` returns a string in the format `Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)`, while `toDateString()` and `toTimeString()` return the date and time parts of the string, respectively. `[@@toPrimitive]()` (when passed `"string"` or `"default"`) calls `toString()` and returns the result.
* `toUTCString()` returns a string in the format `Thu, 01 Jan 1970 00:00:00 GMT` (generalized RFC 7231).
* `toLocaleDateString()`, `toLocaleTimeString()`, and `toLocaleString()` use locale-specific date and time formats, usually provided by the `Intl` API.

See the Formats of `toString` method return values section for examples.

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

`Date()`

When called as a constructor, returns a new `Date` object. When called as a function, returns a string representation of the current date and time.

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

`Date.now()`

Returns the numeric value corresponding to the current time—the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC, with leap seconds ignored.

`Date.parse()`

Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00 UTC, with leap seconds ignored.

`Date.UTC()`

Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored.

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

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

`Date.prototype.constructor`

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

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

`Date.prototype.getDate()`

Returns the day of the month (`1` – `31`) for the specified date according to local time.

`Date.prototype.getDay()`

Returns the day of the week (`0` – `6`) for the specified date according to local time.

`Date.prototype.getFullYear()`

Returns the year (4 digits for 4-digit years) of the specified date according to local time.

`Date.prototype.getHours()`

Returns the hour (`0` – `23`) in the specified date according to local time.

`Date.prototype.getMilliseconds()`

Returns the milliseconds (`0` – `999`) in the specified date according to local time.

`Date.prototype.getMinutes()`

Returns the minutes (`0` – `59`) in the specified date according to local time.

`Date.prototype.getMonth()`

Returns the month (`0` – `11`) in the specified date according to local time.

`Date.prototype.getSeconds()`

Returns the seconds (`0` – `59`) in the specified date according to local time.

`Date.prototype.getTime()`

Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)

`Date.prototype.getTimezoneOffset()`

Returns the time-zone offset in minutes for the current locale.

`Date.prototype.getUTCDate()`

Returns the day (date) of the month (`1` – `31`) in the specified date according to universal time.

`Date.prototype.getUTCDay()`

Returns the day of the week (`0` – `6`) in the specified date according to universal time.

`Date.prototype.getUTCFullYear()`

Returns the year (4 digits for 4-digit years) in the specified date according to universal time.

`Date.prototype.getUTCHours()`

Returns the hours (`0` – `23`) in the specified date according to universal time.

`Date.prototype.getUTCMilliseconds()`

Returns the milliseconds (`0` – `999`) in the specified date according to universal time.

`Date.prototype.getUTCMinutes()`

Returns the minutes (`0` – `59`) in the specified date according to universal time.

`Date.prototype.getUTCMonth()`

Returns the month (`0` – `11`) in the specified date according to universal time.

`Date.prototype.getUTCSeconds()`

Returns the seconds (`0` – `59`) in the specified date according to universal time.

`Date.prototype.getYear()`
Deprecated

Returns the year (usually 2–3 digits) in the specified date according to local time. Use `getFullYear()` instead.

`Date.prototype.setDate()`

Sets the day of the month for a specified date according to local time.

`Date.prototype.setFullYear()`

Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to local time.

`Date.prototype.setHours()`

Sets the hours for a specified date according to local time.

`Date.prototype.setMilliseconds()`

Sets the milliseconds for a specified date according to local time.

`Date.prototype.setMinutes()`

Sets the minutes for a specified date according to local time.

`Date.prototype.setMonth()`

Sets the month for a specified date according to local time.

`Date.prototype.setSeconds()`

Sets the seconds for a specified date according to local time.

`Date.prototype.setTime()`

Sets the `Date` object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. Use negative numbers for times prior.

`Date.prototype.setUTCDate()`

Sets the day of the month for a specified date according to universal time.

`Date.prototype.setUTCFullYear()`

Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to universal time.

`Date.prototype.setUTCHours()`

Sets the hour for a specified date according to universal time.

`Date.prototype.setUTCMilliseconds()`

Sets the milliseconds for a specified date according to universal time.

`Date.prototype.setUTCMinutes()`

Sets the minutes for a specified date according to universal time.

`Date.prototype.setUTCMonth()`

Sets the month for a specified date according to universal time.

`Date.prototype.setUTCSeconds()`

Sets the seconds for a specified date according to universal time.

`Date.prototype.setYear()`
Deprecated

Sets the year (usually 2–3 digits) for a specified date according to local time. Use `setFullYear()` instead.

`Date.prototype.toDateString()`

Returns the "date" portion of the `Date` as a human-readable string like `'Thu Apr 12 2018'`.

`Date.prototype.toISOString()`

Converts a date to a string following the ISO 8601 Extended Format.

`Date.prototype.toJSON()`

Returns a string representing the `Date` using `toISOString()`. Intended for use by `JSON.stringify()`.

`Date.prototype.toLocaleDateString()`

Returns a string with a locality sensitive representation of the date portion of this date based on system settings.

`Date.prototype.toLocaleString()`

Returns a string with a locality-sensitive representation of this date. Overrides the `Object.prototype.toLocaleString()` method.

`Date.prototype.toLocaleTimeString()`

Returns a string with a locality-sensitive representation of the time portion of this date, based on system settings.

`Date.prototype.toString()`

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

`Date.prototype.toTimeString()`

Returns the "time" portion of the `Date` as a human-readable string.

`Date.prototype.toUTCString()`

Converts a date to a string using the UTC timezone.

`Date.prototype.valueOf()`

Returns the primitive value of a `Date` object. Overrides the `Object.prototype.valueOf()` method.

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

Converts this `Date` object to a primitive value.

Examples
--------

### Several ways to create a Date object

The following examples show several ways to create JavaScript dates:

**Note:** Creating a date from a string has a lot of behavior inconsistencies. See date time string format for caveats on using different formats.

```js
const today = new Date();
const birthday = new Date("December 17, 1995 03:24:00"); // DISCOURAGED: may not work in all runtimes
const birthday2 = new Date("1995-12-17T03:24:00"); // This is standardized and will work reliably
const birthday3 = new Date(1995, 11, 17); // the month is 0-indexed
const birthday4 = new Date(1995, 11, 17, 3, 24, 0);
const birthday5 = new Date(628021800000); // passing epoch timestamp
```

### Formats of toString method return values

```js
const date = new Date("2020-05-12T23:50:21.817Z");
date.toString(); // Tue May 12 2020 18:50:21 GMT-0500 (Central Daylight Time)
date.toDateString(); // Tue May 12 2020
date.toTimeString(); // 18:50:21 GMT-0500 (Central Daylight Time)
date[Symbol.toPrimitive]("string"); // Tue May 12 2020 18:50:21 GMT-0500 (Central Daylight Time)

date.toISOString(); // 2020-05-12T23:50:21.817Z
date.toJSON(); // 2020-05-12T23:50:21.817Z

date.toUTCString(); // Tue, 12 May 2020 23:50:21 GMT

date.toLocaleString(); // 5/12/2020, 6:50:21 PM
date.toLocaleDateString(); // 5/12/2020
date.toLocaleTimeString(); // 6:50:21 PM
```

### To get Date, Month and Year or Time

```js
const date = new Date("2000-01-17T16:45:30");
const [month, day, year] = [
  date.getMonth(),
  date.getDate(),
  date.getFullYear(),
];
// [0, 17, 2000] as month are 0-indexed
const [hour, minutes, seconds] = [
  date.getHours(),
  date.getMinutes(),
  date.getSeconds(),
];
// [16, 45, 30]
```

### Interpretation of two-digit years

`new Date()` exhibits legacy undesirable, inconsistent behavior with two-digit year values; specifically, when a `new Date()` call is given a two-digit year value, that year value does not get treated as a literal year and used as-is but instead gets interpreted as a relative offset — in some cases as an offset from the year `1900`, but in other cases, as an offset from the year `2000`.

```js
let date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
date = new Date(22, 1); // Wed Feb 01 1922 00:00:00 GMT+0000 (GMT)
date = new Date("2/1/22"); // Tue Feb 01 2022 00:00:00 GMT+0000 (GMT)

// Legacy method; always interprets two-digit year values as relative to 1900
date.setYear(98);
date.toString(); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
date.setYear(22);
date.toString(); // Wed Feb 01 1922 00:00:00 GMT+0000 (GMT)
```

So, to create and get dates between the years `0` and `99`, instead use the preferred `setFullYear()` and `getFullYear()` methods:.

```js
// Preferred method; never interprets any value as being a relative offset,
// but instead uses the year value as-is
date.setFullYear(98);
date.getFullYear(); // 98 (not 1998)
date.setFullYear(22);
date.getFullYear(); // 22 (not 1922, not 2022)
```

### Calculating elapsed time

The following examples show how to determine the elapsed time between two JavaScript dates in milliseconds.

Due to the differing lengths of days (due to daylight saving changeover), months, and years, expressing elapsed time in units greater than hours, minutes, and seconds requires addressing a number of issues, and should be thoroughly researched before being attempted.

```js
// Using Date objects
const start = Date.now();

// The event to time goes here:
doSomethingForALongTime();
const end = Date.now();
const elapsed = end - start; // elapsed time in milliseconds
```

```js
// Using built-in methods
const start = new Date();

// The event to time goes here:
doSomethingForALongTime();
const end = new Date();
const elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
```

```js
// To test a function and get back its return
function printElapsedTime(testFn) {
  const startTime = Date.now();
  const result = testFn();
  const endTime = Date.now();

  console.log(`Elapsed time: ${String(endTime - startTime)} milliseconds`);
  return result;
}

const yourFunctionReturn = printElapsedTime(yourFunction);
```

**Note:** In browsers that support the Web Performance API's high-resolution time feature, `Performance.now()` can provide more reliable and precise measurements of elapsed time than `Date.now()`.

### Get the number of seconds since the ECMAScript Epoch

```js
const seconds = Math.floor(Date.now() / 1000);
```

In this case, it's important to return only an integer—so a simple division won't do. It's also important to only return actually elapsed seconds. (That's why this code uses `Math.floor()`, and *not* `Math.round()`.)

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

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

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

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

See also
--------

* `Date()`


InternalError - JavaScript

InternalError
=============

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

The **`InternalError`** object indicates an error that occurred internally in the JavaScript engine.

Example cases are mostly when something is too large, e.g.:

* "too many switch cases",
* "too many parentheses in regular expression",
* "array initializer too large",
* "too much recursion".

`InternalError` is a subclass of `Error`.

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

`InternalError()`
Non-standard

Creates a new `InternalError` object.

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

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

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

`InternalError.prototype.constructor`

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

`InternalError.prototype.name`

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

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

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

Examples
--------

### Too much recursion

This recursive function runs 10 times, as per the exit condition.

```js
function loop(x) {
  // "x >= 10" is the exit condition
  if (x >= 10) return;

  // do stuff
  loop(x + 1); // the recursive call
}
loop(0);
```

Setting this condition to an extremely high value, may not work:

```js
function loop(x) {
  if (x >= 1000000000000) return;

  // do stuff
  loop(x + 1);
}
loop(0);

// InternalError: too much recursion
```

For more information, see InternalError: too much recursion.

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

Not part of any standard.

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

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

See also
--------

* `Error`
* InternalError: too much recursion


WeakMap - JavaScript

WeakMap
=======

A **`WeakMap`** is a collection of key/value pairs whose keys must be objects or non-registered symbols, with values of any arbitrary JavaScript type, and which does not create strong references to its keys. That is, an object's presence as a key in a `WeakMap` does not prevent the object from being garbage collected. Once an object used as a key has been collected, its corresponding values in any `WeakMap` become candidates for garbage collection as well — as long as they aren't strongly referred to elsewhere. The only primitive type that can be used as a `WeakMap` key is symbol — more specifically, non-registered symbols — because non-registered symbols are guaranteed to be unique and cannot be re-created.

`WeakMap` allows associating data to objects in a way that doesn't prevent the key objects from being collected, even if the values reference the keys. However, a `WeakMap` doesn't allow observing the liveness of its keys, which is why it doesn't allow enumeration; if a `WeakMap` exposed any method to obtain a list of its keys, the list would depend on the state of garbage collection, introducing non-determinism. If you want to have a list of keys, you should use a `Map` rather than a `WeakMap`.

You can learn more about `WeakMap` in the WeakMap object section of the Keyed collections guide.

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

Keys of WeakMaps must be garbage-collectable. Most primitive data types can be arbitrarily created and don't have a lifetime, so they cannot be used as keys. Objects and non-registered symbols can be used as keys because they are garbage-collectable.

### Why WeakMap?

A map API *could* be implemented in JavaScript with two arrays (one for keys, one for values) shared by the four API methods. Setting elements on this map would involve pushing a key and value onto the end of each of those arrays simultaneously. As a result, the indices of the key and value would correspond to both arrays. Getting values from the map would involve iterating through all keys to find a match, then using the index of this match to retrieve the corresponding value from the array of values.

Such an implementation would have two main inconveniences:

1. The first one is an `O(n)` set and search (*n* being the number of keys in the map) since both operations must iterate through the list of keys to find a matching value.
2. The second inconvenience is a memory leak because the arrays ensure that references to each key and each value are maintained indefinitely. These references prevent the keys from being garbage collected, even if there are no other references to the object. This would also prevent the corresponding values from being garbage collected.

By contrast, in a `WeakMap`, a key object refers strongly to its contents as long as the key is not garbage collected, but weakly from then on. As such, a `WeakMap`:

* does not prevent garbage collection, which eventually removes references to the key object
* allows garbage collection of any values if their key objects are not referenced from somewhere other than a `WeakMap`

A `WeakMap` can be a particularly useful construct when mapping keys to information about the key that is valuable *only if* the key has not been garbage collected.

But because a `WeakMap` doesn't allow observing the liveness of its keys, its keys are not enumerable. There is no method to obtain a list of the keys. If there were, the list would depend on the state of garbage collection, introducing non-determinism. If you want to have a list of keys, you should use a `Map`.

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

`WeakMap()`

Creates a new `WeakMap` object.

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

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

`WeakMap.prototype.constructor`

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

`WeakMap.prototype[@@toStringTag]`

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

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

`WeakMap.prototype.delete()`

Removes any value associated to the `key`. `WeakMap.prototype.has(key)` will return `false` afterwards.

`WeakMap.prototype.get()`

Returns the value associated to the `key`, or `undefined` if there is none.

`WeakMap.prototype.has()`

Returns a Boolean asserting whether a value has been associated to the `key` in the `WeakMap` object or not.

`WeakMap.prototype.set()`

Sets the `value` for the `key` in the `WeakMap` object. Returns the `WeakMap` object.

Examples
--------

### Using WeakMap

```js
const wm1 = new WeakMap();
const wm2 = new WeakMap();
const wm3 = new WeakMap();
const o1 = {};
const o2 = function () {};
const o3 = window;

wm1.set(o1, 37);
wm1.set(o2, "azerty");
wm2.set(o1, o2); // a value can be anything, including an object or a function
wm2.set(o2, undefined);
wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps!

wm1.get(o2); // "azerty"
wm2.get(o2); // undefined, because that is the set value
wm2.get(o3); // undefined, because there is no key for o3 on wm2

wm1.has(o2); // true
wm2.has(o2); // true (even if the value itself is 'undefined')
wm2.has(o3); // false

wm3.set(o1, 37);
wm3.get(o1); // 37

wm1.has(o1); // true
wm1.delete(o1);
wm1.has(o1); // false
```

### Implementing a WeakMap-like class with a .clear() method

```js
class ClearableWeakMap {
  #wm;
  constructor(init) {
    this.#wm = new WeakMap(init);
  }
  clear() {
    this.#wm = new WeakMap();
  }
  delete(k) {
    return this.#wm.delete(k);
  }
  get(k) {
    return this.#wm.get(k);
  }
  has(k) {
    return this.#wm.has(k);
  }
  set(k, v) {
    this.#wm.set(k, v);
    return this;
  }
}
```

### Emulating private members

Developers can use a `WeakMap` to associate private data to an object, with the following benefits:

* Compared to a `Map`, a WeakMap does not hold strong references to the object used as the key, so the metadata shares the same lifetime as the object itself, avoiding memory leaks.
* Compared to using non-enumerable and/or `Symbol` properties, a WeakMap is external to the object and there is no way for user code to retrieve the metadata through reflective methods like `Object.getOwnPropertySymbols`.
* Compared to a closure, the same WeakMap can be reused for all instances created from a constructor, making it more memory-efficient, and allows different instances of the same class to read the private members of each other.

```js
let Thing;

{
  const privateScope = new WeakMap();
  let counter = 0;

  Thing = function () {
    this.someProperty = "foo";

    privateScope.set(this, {
      hidden: ++counter,
    });
  };

  Thing.prototype.showPublic = function () {
    return this.someProperty;
  };

  Thing.prototype.showPrivate = function () {
    return privateScope.get(this).hidden;
  };
}

console.log(typeof privateScope);
// "undefined"

const thing = new Thing();

console.log(thing);
// Thing {someProperty: "foo"}

thing.showPublic();
// "foo"

thing.showPrivate();
// 1
```

This is roughly equivalent to the following, using private fields:

```js
class Thing {
  static #counter = 0;
  #hidden;
  constructor() {
    this.someProperty = "foo";
    this.#hidden = ++Thing.#counter;
  }
  showPublic() {
    return this.someProperty;
  }
  showPrivate() {
    return this.#hidden;
  }
}

console.log(thing);
// Thing {someProperty: "foo"}

thing.showPublic();
// "foo"

thing.showPrivate();
// 1
```

### Associating metadata

A `WeakMap` can be used to associate metadata with an object, without affecting the lifetime of the object itself. This is very similar to the private members example, since private members are also modelled as external metadata that doesn't participate in prototypical inheritance.

This use case can be extended to already-created objects. For example, on the web, we may want to associate extra data with a DOM element, which the DOM element may access later. A common approach is to attach the data as a property:

```js
const buttons = document.querySelectorAll(".button");
buttons.forEach((button) => {
  button.clicked = false;
  button.addEventListener("click", () => {
    button.clicked = true;
    const currentButtons = [...document.querySelectorAll(".button")];
    if (currentButtons.every((button) => button.clicked)) {
      console.log("All buttons have been clicked!");
    }
  });
});
```

This approach works, but it has a few pitfalls:

* The `clicked` property is enumerable, so it will show up in `Object.keys(button)`, `for...in` loops, etc. This can be mitigated by using `Object.defineProperty()`, but that makes the code more verbose.
* The `clicked` property is a normal string property, so it can be accessed and overwritten by other code. This can be mitigated by using a `Symbol` key, but the key would still be accessible via `Object.getOwnPropertySymbols()`.

Using a `WeakMap` fixes these:

```js
const buttons = document.querySelectorAll(".button");
const clicked = new WeakMap();
buttons.forEach((button) => {
  clicked.set(button, false);
  button.addEventListener("click", () => {
    clicked.set(button, true);
    const currentButtons = [...document.querySelectorAll(".button")];
    if (currentButtons.every((button) => clicked.get(button))) {
      console.log("All buttons have been clicked!");
    }
  });
});
```

Here, only code that has access to `clicked` knows the clicked state of each button, and external code can't modify the states. In addition, if any of the buttons gets removed from the DOM, the associated metadata will automatically get garbage-collected.

### Caching

You can associate objects passed to a function with the result of the function, so that if the same object is passed again, the cached result can be returned without re-executing the function. This is useful if the function is pure (i.e. it doesn't mutate any outside objects or cause other observable side effects).

```js
const cache = new WeakMap();
function handleObjectValues(obj) {
  if (cache.has(obj)) {
    return cache.get(obj);
  }
  const result = Object.values(obj).map(heavyComputation);
  cache.set(obj, result);
  return result;
}
```

This only works if your function's input is an object. Moreover, even if the input is never passed in again, the result still remains forever in the cache. A more effective way is to use a `Map` paired with `WeakRef` objects, which allows you to associate any type of input value with its respective (potentially large) computation result. See the WeakRefs and FinalizationRegistry example for more details.

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

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

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

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

See also
--------

* Polyfill of `WeakMap` in `core-js`
* Keyed collections
* Hiding Implementation Details with ECMAScript 6 WeakMaps by Nick Fitzgerald (2014)
* `Map`
* `Set`
* `WeakSet`


Intl - JavaScript

Intl
====

The **`Intl`** namespace object contains several constructors as well as functionality common to the internationalization constructors and other language sensitive functions. Collectively, they comprise the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, date and time formatting, and more.

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

Unlike most global objects, `Intl` is not a constructor. You cannot use it with the `new` operator or invoke the `Intl` object as a function. All properties and methods of `Intl` are static (just like the `Math` object).

The internationalization constructors as well as several language sensitive methods of other constructors (listed under See also) use a common pattern for identifying locales and determining the one they will actually use: they all accept `locales` and `options` arguments, and negotiate the requested locale(s) against the locales they support using an algorithm specified in the `options.localeMatcher` property.

### locales argument

The `locales` argument is used to determine the locale used in a given operation. The JavaScript implementation examines `locales`, and then computes a locale it understands that comes closest to satisfying the expressed preference. `locales` may be:

* `undefined` (or omitted): The implementation's default locale will be used.
* A locale: A locale identifier or an `Intl.Locale` object that wraps a locale identifier.
* A list of locales: Any other value, that will be converted into an object and then treated as an array of locales.

In the latter two cases, the actual locale used is the best-supported locale determined by locale negotiation. If a locale identifier is not a string or an object, a `TypeError` is thrown. If a locale identifier is a string that's syntactically invalid, a `RangeError` is thrown. If a locale identifier is well-formed but the implementation doesn't recognize it, it is ignored and the next locale in the list is considered, eventually falling back to the system's locale. However, you shouldn't rely on a particular locale name being ignored, because the implementation may add data for any locale in the future. For example, `new Intl.DateTimeFormat("default")` uses the implementation's default locale only because `"default"` is syntactically valid but not recognized as any locale.

A locale identifier is a string that consists of:

1. A language subtag with 2–3 or 5–8 letters
2. A script subtag with 4 letters Optional
3. A region subtag with either 2 letters or 3 digits Optional
4. One or more variant subtags (all of which must be unique), each with either 5–8 alphanumerals or a digit followed by 3 alphanumerals Optional
5. One or more BCP 47 extension sequences Optional
6. A private-use extension sequence Optional

Each subtag and sequence are separated by hyphens. Locale identifiers are case-insensitive ASCII. However, it's conventional to use title case (the first letter is capitalized, successive letters are lower case) for script subtags, upper case for region subtags, and lower case for everything else. For example:

* `"hi"`: Hindi (language)
* `"de-AT"`: German (language) as used in Austria (region)
* `"zh-Hans-CN"`: Chinese (language) written in simplified characters (script) as used in China (region)
* `"en-emodeng"`: English (language) in the "Early modern English" dialect (variant)

Subtags identifying languages, scripts, regions (including countries), and (rarely used) variants are registered in the IANA Language Subtag Registry. This registry is periodically updated over time, and implementations may not always be up to date, so don't rely too much on subtags being universally supported.

BCP 47 extension sequences consist of a single digit or letter (other than `"x"`) and one or more two- to eight-letter or digit subtags separated by hyphens. Only one sequence is permitted for each digit or letter: `"de-a-foo-a-foo"` is invalid. BCP 47 extension subtags are defined in the Unicode CLDR Project. Currently only two extensions have defined semantics:

* The `"u"` (Unicode) extension can be used to request additional customization of `Intl` API objects. Examples:
    + `"de-DE-u-co-phonebk"`: Use the phonebook variant of the German sort order, which interprets umlauted vowels as corresponding character pairs: ä → ae, ö → oe, ü → ue.
    + `"th-TH-u-nu-thai"`: Use Thai digits (๐, ๑, ๒, ๓, ๔, ๕, ๖, ๗, ๘, ๙) in number formatting.
    + `"ja-JP-u-ca-japanese"`: Use the Japanese calendar in date and time formatting, so that 2013 is expressed as the year 25 of the Heisei period, or 平成 25.
    + `"en-GB-u-ca-islamic"`: use British English with the Islamic (Hijri) calendar, where the Gregorian date 14 October, 2017 is the Hijri date 24 Muharram, 1439.
* The `"t"` (transformed) extension indicates transformed content: for example, text that was translated from another locale. No `Intl` functionality currently considers the `"t"` extension. However, this extension sometimes contains a nested locale (with no extensions): for example, the transformed extension in `"de-t-en"` contains the locale identifier for English. If a nested locale is present, it must be a valid locale identifier. For example, because `"en-emodeng-emodeng"` is invalid (because it contains a duplicate `emodeng` variant subtag), `"de-t-en-emodeng-emodeng"` is also invalid.

Finally, a private-use extension sequence using the letter `"x"` may appear, followed by one or more one- to eight-letter or digit subtags separated by hyphens. This allows applications to encode information for their own private use, that will be ignored by all `Intl` operations.

### options argument

The `options` argument must be an object with properties that vary between constructors and functions. If the `options` argument is not provided or is undefined, default values are used for all properties.

One property is supported by all language sensitive constructors and functions: The `localeMatcher` property, whose value must be a string `"lookup"` or `"best fit"` and which selects one of the locale matching algorithms described below.

### Locale identification and negotiation

The list of locales specified by the `locales` argument, after Unicode extensions have been removed from them, is interpreted as a prioritized request from the application. The runtime compares it against the locales it has available and picks the best one available. Two matching algorithms exist: the `"lookup"` matcher follows the Lookup algorithm specified in BCP 47; the `"best fit"` matcher lets the runtime provide a locale that's at least, but possibly more, suited for the request than the result of the Lookup algorithm. If the application doesn't provide a `locales` argument, or the runtime doesn't have a locale that matches the request, then the runtime's default locale is used. The matcher can be selected using a property of the `options` argument (see below).

If the selected locale identifier had a Unicode extension sequence, that extension is now used to customize the constructed object or the behavior of the function. Each constructor or function supports only a subset of the keys defined for the Unicode extension, and the supported values often depend on the locale identifier. For example, the `"co"` key (collation) is only supported by `Intl.Collator`, and its `"phonebk"` value is only supported for German.

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

`Intl.Collator`

Constructor for collators, which are objects that enable language-sensitive string comparison.

`Intl.DateTimeFormat`

Constructor for objects that enable language-sensitive date and time formatting.

`Intl.DisplayNames`

Constructor for objects that enable the consistent translation of language, region and script display names.

`Intl.DurationFormat`
Experimental

Constructor for objects that enable locale-sensitive duration formatting.

`Intl.ListFormat`

Constructor for objects that enable language-sensitive list formatting.

`Intl.Locale`

Constructor for objects that represents a Unicode locale identifier.

`Intl.NumberFormat`

Constructor for objects that enable language-sensitive number formatting.

`Intl.PluralRules`

Constructor for objects that enable plural-sensitive formatting and language-specific rules for plurals.

`Intl.RelativeTimeFormat`

Constructor for objects that enable language-sensitive relative time formatting.

`Intl.Segmenter`

Constructor for objects that enable locale-sensitive text segmentation.

`Intl[@@toStringTag]`

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

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

`Intl.getCanonicalLocales()`

Returns canonical locale names.

`Intl.supportedValuesOf()`

Returns a sorted array containing the supported unique calendar, collation, currency, numbering systems, or unit values supported by the implementation.

Examples
--------

### Formatting dates and numbers

You can use `Intl` to format dates and numbers in a form that's conventional for a specific language and region:

```js
const count = 26254.39;
const date = new Date("2012-05-24");

function log(locale) {
  console.log(
    `${new Intl.DateTimeFormat(locale).format(date)} ${new Intl.NumberFormat(
 locale,
 ).format(count)}`,
  );
}

log("en-US"); // 5/24/2012 26,254.39

log("de-DE"); // 24.5.2012 26.254,39
```

### Using the browser's preferred language

Instead of passing a hardcoded locale name to the `Intl` methods, you can use the user's preferred language provided by `navigator.language`:

```js
const date = new Date("2012-05-24");

const formattedDate = new Intl.DateTimeFormat(navigator.language).format(date);
```

Alternatively, the `navigator.languages` property provides a sorted list of the user's preferred languages. This list can be passed directly to the `Intl` constructors to implement preference-based fallback selection of locales. The locale negotiation process is used to pick the most appropriate locale available:

```js
const count = 26254.39;

const formattedCount = new Intl.NumberFormat(navigator.languages).format(count);
```

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

| Specification |
| --- |
| ECMAScript Internationalization API Specification # intl-object |

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

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

See also
--------

* `String.prototype.localeCompare()`
* `Number.prototype.toLocaleString()`
* `Date.prototype.toLocaleString()`
* `Date.prototype.toLocaleDateString()`
* `Date.prototype.toLocaleTimeString()`
* `navigator.language`
* `navigator.languages`
* The ECMAScript Internationalization API by Norbert Lindenberg (2012)


ReferenceError - JavaScript

ReferenceError
==============

The **`ReferenceError`** object represents an error when a variable that doesn't exist (or hasn't yet been initialized) in the current scope is referenced.

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

`ReferenceError` is a subclass of `Error`.

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

`ReferenceError()`

Creates a new `ReferenceError` object.

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

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

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

`ReferenceError.prototype.constructor`

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

`ReferenceError.prototype.name`

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

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

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

Examples
--------

### Catching a ReferenceError

```js
try {
  let a = undefinedVariable;
} catch (e) {
  console.log(e instanceof ReferenceError); // true
  console.log(e.message); // "undefinedVariable is not defined"
  console.log(e.name); // "ReferenceError"
  console.log(e.stack); // Stack of the error
}
```

### Creating a ReferenceError

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

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

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

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

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

See also
--------

* `Error`


undefined - JavaScript

undefined
=========

 The **`undefined`** global property represents the primitive
 value `undefined`. It is one of JavaScript's
 primitive types.

Try it
------

Value
-----

The primitive value `undefined`.

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

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

`undefined` is a property of the *global object*. That is, it is a variable in global scope.

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

 A variable that has not been assigned a value is of type `undefined`. A
 method or statement also returns `undefined` if the variable that is being
 evaluated does not have an assigned value. A function returns `undefined` if
 a value was not `returned`.

**Note:** While you can use `undefined` as an identifier (variable name) in any scope other than the global scope (because `undefined` is not a reserved word), doing so is a very bad idea that will make your code difficult to maintain and debug.

```js
// DON'T DO THIS

(() => {
  const undefined = "foo";
  console.log(undefined, typeof undefined); // foo string
})();

((undefined) => {
  console.log(undefined, typeof undefined); // foo string
})("foo");
```

Examples
--------

### Strict equality and undefined

 You can use `undefined` and the strict equality and inequality operators to
 determine whether a variable has a value. In the following code, the variable
 `x` is not initialized, and the `if` statement evaluates to true.

```js
let x;
if (x === undefined) {
  // these statements execute
} else {
  // these statements do not execute
}
```

**Note:** The *strict equality* operator (as opposed to the
 *standard equality* operator) must be used here, because
 `x == undefined` also checks whether `x` is `null`,
 while strict equality doesn't. This is because `null` is not equivalent to
 `undefined`.

See Equality comparison and sameness for details.

### typeof operator and undefined

Alternatively, `typeof` can be used:

```js
let x;
if (typeof x === "undefined") {
  // these statements execute
}
```

 One reason to use `typeof` is that it does not throw an
 error if the variable has not been declared.

```js
// x has not been declared before
// evaluates to true without errors
if (typeof x === "undefined") {
  // these statements execute
}

// Throws a ReferenceError
if (x === undefined) {
}
```

 However, there is another alternative. JavaScript is a statically scoped language, so
 knowing if a variable is declared can be read by seeing whether it is declared in an
 enclosing context.

 The global scope is bound to the global object, so
 checking the existence of a variable in the global context can be done by checking the
 existence of a property on the *global object*, using the
 `in` operator, for instance:

```js
if ("x" in window) {
  // These statements execute only if x is defined globally
}
```

### void operator and undefined

The `void` operator is a third alternative.

```js
let x;
if (x === void 0) {
  // these statements execute
}

// y has not been declared before
if (y === void 0) {
  // throws Uncaught ReferenceError: y is not defined
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-undefined |

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

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

See also
--------

* JavaScript data types and data structures
* `null`


globalThis - JavaScript

globalThis
==========

The **`globalThis`** global property contains the global `this` value, which is usually akin to the global object.

Try it
------

Value
-----

The global `this` object.

| Property attributes of `globalThis` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |

**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 `window`, `self`, or `frames` - but in Web Workers 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 `eval()`, like CSP in browsers, prevent use of `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 `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 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.

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 violations in some settings, so authors would use a piecewise definition like this (slightly adapted from the original core-js source):

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-globalthis |

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

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

See also
--------

* Polyfill of `globalThis` in `core-js`
* `this`


Uint32Array - JavaScript

Uint32Array
===========

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

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

`Uint32Array()`

Creates a new `Uint32Array` object.

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

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

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

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

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

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

`Uint32Array.prototype.BYTES_PER_ELEMENT`

Returns a number value of the element size. `4` in the case of a `Uint32Array`.

`Uint32Array.prototype.constructor`

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

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

*Inherits instance methods from its parent `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
--------------

| 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 `Uint32Array` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `ArrayBuffer`
* `DataView`


encodeURI() - JavaScript

encodeURI()
===========

The **`encodeURI()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to `encodeURIComponent()`, this function encodes fewer characters, preserving those that are part of the URI syntax.

Try it
------

Syntax
------

```js
encodeURI(uri)
```

### Parameters

`uri`

A string to be encoded as a URI.

### Return value

A new string representing the provided string encoded as a URI.

### Exceptions

`URIError`

Thrown if `uri` contains a lone surrogate.

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

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

The `encodeURI()` function escapes characters by UTF-8 code units, with each octet encoded in the format `%XX`, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause `encodeURI()` to throw a `URIError`.

`encodeURI()` escapes all characters **except**:
```

A–Z a–z 0–9 - _ . ! ~ * ' ( )

; / ? : @ & = + $ , #
```

The characters on the second line are characters that may be part of the URI syntax, and are only escaped by `encodeURIComponent()`. Both `encodeURI()` and `encodeURIComponent()` do not encode the characters `-.!~*'()`, known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See RFC2396)

The `encodeURI()` function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning:

```url
http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor
```

`encodeURI`, as the name implies, is used to encode a URL as a whole, assuming it is already well-formed. If you want to dynamically assemble string values into a URL, you probably want to use `encodeURIComponent()` on each dynamic segment instead, to avoid URL syntax characters in unwanted places.

```js
const name = "Ben & Jerry's";

// This is bad:
const link = encodeURI(`https://example.com/?choice=${name}`); // "https://example.com/?choice=Ben%20&%20Jerry's"
console.log([...new URL(link).searchParams]); // [['choice', 'Ben '], [" Jerry's", '']

// Instead:
const link = encodeURI(
  `https://example.com/?choice=${encodeURIComponent(name)}`,
);
// "https://example.com/?choice=Ben%2520%2526%2520Jerry's"
console.log([...new URL(link).searchParams]); // [['choice', "Ben%20%26%20Jerry's"]]
```

Examples
--------

### encodeURI() vs. encodeURIComponent()

`encodeURI()` differs from `encodeURIComponent()` as follows:

```js
const set1 = ";/?:@&=+$,#"; // Reserved Characters
const set2 = "-.!~\*'()"; // Unreserved Marks
const set3 = "ABC abc 123"; // Alphanumeric Characters + Space

console.log(encodeURI(set1)); // ;/?:@&=+$,#
console.log(encodeURI(set2)); // -.!~\*'()
console.log(encodeURI(set3)); // ABC%20abc%20123 (the space gets encoded as %20)

console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24%23
console.log(encodeURIComponent(set2)); // -.!~\*'()
console.log(encodeURIComponent(set3)); // ABC%20abc%20123 (the space gets encoded as %20)
```

### Encoding a lone surrogate throws

A `URIError` will be thrown if one attempts to encode a surrogate which is not part of a high-low pair. For example:

```js
// High-low pair OK
encodeURI("\uD800\uDFFF"); // "%F0%90%8F%BF"

// Lone high-surrogate code unit throws "URIError: malformed URI sequence"
encodeURI("\uD800");

// Lone low-surrogate code unit throws "URIError: malformed URI sequence"
encodeURI("\uDFFF");
```

You can use `String.prototype.toWellFormed()`, which replaces lone surrogates with the Unicode replacement character (U+FFFD), to avoid this error. You can also use `String.prototype.isWellFormed()` to check if a string contains lone surrogates before passing it to `encodeURI()`.

### Encoding for RFC3986

The more recent RFC3986 makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host). It also reserves !, ', (, ), and \*, even though these characters have no formalized URI delimiting uses. The following function encodes a string for RFC3986-compliant URL format.

```js
function encodeRFC3986URI(str) {
  return encodeURI(str)
    .replace(/%5B/g, "[")
    .replace(/%5D/g, "]")
    .replace(
      /[!'()\*]/g,
      (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
    );
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-encodeuri-uri |

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

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

See also
--------

* `decodeURI()`
* `encodeURIComponent()`
* `decodeURIComponent()`


RangeError - JavaScript

RangeError
==========

The **`RangeError`** object indicates an error when a value is not in the set or range of allowed values.

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

A `RangeError` is thrown when trying to pass a value as an argument to a function that does not allow a range that includes the value.

This can be encountered when:

* passing a value that is not one of the allowed string values to `String.prototype.normalize()`, or
* when attempting to create an array of an illegal length with the `Array` constructor, or
* when passing bad values to the numeric methods `Number.prototype.toExponential()`, `Number.prototype.toFixed()` or `Number.prototype.toPrecision()`.

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

`RangeError` is a subclass of `Error`.

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

`RangeError()`

Creates a new `RangeError` object.

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

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

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

`RangeError.prototype.constructor`

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

`RangeError.prototype.name`

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

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

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

Examples
--------

### Using RangeError (for numeric values)

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

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

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

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

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

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

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

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

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

See also
--------

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


BigInt64Array - JavaScript

BigInt64Array
=============

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

Try it
------

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

`BigInt64Array()`

Creates a new `BigInt64Array` object.

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

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

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

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

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

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

`BigInt64Array.prototype.BYTES_PER_ELEMENT`

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

`BigInt64Array.prototype.constructor`

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

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

*Inherits instance methods from its parent `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
--------------

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


Math - JavaScript

Math
====

The **`Math`** namespace object contains static properties and methods for mathematical constants and functions.

`Math` works with the `Number` type. It doesn't work with `BigInt`.

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

Unlike most global objects, `Math` is not a constructor. You cannot use it with the `new` operator or invoke the `Math` object as a function. All properties and methods of `Math` are static.

**Note:** Many `Math` functions have a precision that's *implementation-dependent*.

This means that different browsers can give a different result. Even the same JavaScript engine on a different OS or architecture can give different results!

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

`Math.E`

Euler's number and the base of natural logarithms; approximately `2.718`.

`Math.LN10`

Natural logarithm of `10`; approximately `2.303`.

`Math.LN2`

Natural logarithm of `2`; approximately `0.693`.

`Math.LOG10E`

Base-10 logarithm of `E`; approximately `0.434`.

`Math.LOG2E`

Base-2 logarithm of `E`; approximately `1.443`.

`Math.PI`

Ratio of a circle's circumference to its diameter; approximately `3.14159`.

`Math.SQRT1_2`

Square root of ½; approximately `0.707`.

`Math.SQRT2`

Square root of `2`; approximately `1.414`.

`Math[@@toStringTag]`

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

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

`Math.abs()`

Returns the absolute value of `x`.

`Math.acos()`

Returns the arccosine of `x`.

`Math.acosh()`

Returns the hyperbolic arccosine of `x`.

`Math.asin()`

Returns the arcsine of `x`.

`Math.asinh()`

Returns the hyperbolic arcsine of a number.

`Math.atan()`

Returns the arctangent of `x`.

`Math.atan2()`

Returns the arctangent of the quotient of its arguments.

`Math.atanh()`

Returns the hyperbolic arctangent of `x`.

`Math.cbrt()`

Returns the cube root of `x`.

`Math.ceil()`

Returns the smallest integer greater than or equal to `x`.

`Math.clz32()`

Returns the number of leading zero bits of the 32-bit integer `x`.

`Math.cos()`

Returns the cosine of `x`.

`Math.cosh()`

Returns the hyperbolic cosine of `x`.

`Math.exp()`

Returns ex, where x is the argument, and e is Euler's number (`2.718`…, the base of the natural logarithm).

`Math.expm1()`

Returns subtracting `1` from `exp(x)`.

`Math.floor()`

Returns the largest integer less than or equal to `x`.

`Math.fround()`

Returns the nearest single precision float representation of `x`.

`Math.hypot()`

Returns the square root of the sum of squares of its arguments.

`Math.imul()`

Returns the result of the 32-bit integer multiplication of `x` and `y`.

`Math.log()`

Returns the natural logarithm (㏒e; also, ㏑) of `x`.

`Math.log10()`

Returns the base-10 logarithm of `x`.

`Math.log1p()`

Returns the natural logarithm (㏒e; also ㏑) of `1 + x` for the number `x`.

`Math.log2()`

Returns the base-2 logarithm of `x`.

`Math.max()`

Returns the largest of zero or more numbers.

`Math.min()`

Returns the smallest of zero or more numbers.

`Math.pow()`

Returns base `x` to the exponent power `y` (that is, `x``y`).

`Math.random()`

Returns a pseudo-random number between `0` and `1`.

`Math.round()`

Returns the value of the number `x` rounded to the nearest integer.

`Math.sign()`

Returns the sign of the `x`, indicating whether `x` is positive, negative, or zero.

`Math.sin()`

Returns the sine of `x`.

`Math.sinh()`

Returns the hyperbolic sine of `x`.

`Math.sqrt()`

Returns the positive square root of `x`.

`Math.tan()`

Returns the tangent of `x`.

`Math.tanh()`

Returns the hyperbolic tangent of `x`.

`Math.trunc()`

Returns the integer portion of `x`, removing any fractional digits.

Examples
--------

### Converting between degrees and radians

The trigonometric functions `sin()`, `cos()`, `tan()`, `asin()`, `acos()`, `atan()`, and `atan2()` expect (and return) angles in *radians*.

Since humans tend to think in degrees, and some functions (such as CSS transforms) can accept degrees, it is a good idea to keep functions handy that convert between the two:

```js
function degToRad(degrees) {
  return degrees \* (Math.PI / 180);
}

function radToDeg(rad) {
  return rad / (Math.PI / 180);
}
```

### Calculating the height of an equilateral triangle

If we want to calculate the height of an equilateral triangle, and we know its side length is 100, we can use the formulae *length of the adjacent multiplied by the tangent of the angle is equal to the opposite.*

![An equilateral triangle where a perpendicular of one edge is drawn from the opposite vertex, forming a right triangle with three sides marked as "adjacent", "opposite", and "hypotenuse". The angle between the "adjacent" and "hypotenuse" sides is 60 degrees.](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trigonometry.png)

In JavaScript, we can do this with the following:

```js
50 \* Math.tan(degToRad(60));
```

We use our `degToRad()` function to convert 60 degrees to radians, as `Math.tan()` expects an input value in radians.

### Returning a random integer between two bounds

This can be achieved with a combination of `Math.random()` and `Math.floor()`:

```js
function random(min, max) {
  const num = Math.floor(Math.random() \* (max - min + 1)) + min;
  return num;
}

random(1, 10);
```

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

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

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

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

See also
--------

* `Number`


Float64Array - JavaScript

Float64Array
============

The **`Float64Array`** typed array represents an array of 64-bit floating point numbers 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).

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

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

`Float64Array()`

Creates a new `Float64Array` object.

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

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

`Float64Array.BYTES_PER_ELEMENT`

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

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

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

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

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

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

`Float64Array.prototype.BYTES_PER_ELEMENT`

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

`Float64Array.prototype.constructor`

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

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

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

Examples
--------

### Different ways to create a Float64Array

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

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

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

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

// From an iterable
const iterable = (function\* () {
  yield\* [1, 2, 3];
})();
const float64FromIterable = new Float64Array(iterable);
console.log(float64FromIterable);
// Float64Array [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 `Float64Array` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `ArrayBuffer`
* `DataView`


encodeURIComponent() - JavaScript

encodeURIComponent()
====================

The **`encodeURIComponent()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to `encodeURI()`, this function encodes more characters, including those that are part of the URI syntax.

Try it
------

Syntax
------

```js
encodeURIComponent(uriComponent)
```

### Parameters

`uriComponent`

A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are converted to strings.

### Return value

A new string representing the provided `uriComponent` encoded as a URI component.

### Exceptions

`URIError`

Thrown if `uriComponent` contains a lone surrogate.

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

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

`encodeURIComponent()` uses the same encoding algorithm as described in `encodeURI()`. It escapes all characters **except**:
```

A–Z a–z 0–9 - _ . ! ~ * ' ( )
```

Compared to `encodeURI()`, `encodeURIComponent()` escapes a larger set of characters. Use `encodeURIComponent()` on user-entered fields from forms `POST`'d to the server — this will encode `&` symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes `Jack & Jill`, without `encodeURIComponent()`, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data.

For `application/x-www-form-urlencoded`, spaces are to be replaced by `+`, so one may wish to follow a `encodeURIComponent()` replacement with an additional replacement of `%20` with `+`.

Examples
--------

### Encoding for Content-Disposition and Link headers

The following example provides the special encoding required within UTF-8 `Content-Disposition` and `Link` server response header parameters (e.g., UTF-8 filenames):

```js
const fileName = "my file(2).txt";
const header = `Content-Disposition: attachment; filename\*=UTF-8''${encodeRFC5987ValueChars(
 fileName,
)}`;

console.log(header);
// "Content-Disposition: attachment; filename\*=UTF-8''my%20file%282%29.txt"

function encodeRFC5987ValueChars(str) {
  return (
    encodeURIComponent(str)
      // The following creates the sequences %27 %28 %29 %2A (Note that
      // the valid encoding of "\*" is %2A, which necessitates calling
      // toUpperCase() to properly encode). Although RFC3986 reserves "!",
      // RFC5987 does not, so we do not need to escape it.
      .replace(
        /['()\*]/g,
        (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
      )
      // The following are not required for percent-encoding per RFC5987,
      // so we can allow for a little better readability over the wire: |`^
      .replace(/%(7C|60|5E)/g, (str, hex) =>
        String.fromCharCode(parseInt(hex, 16)),
      )
  );
}
```

### Encoding for RFC3986

The more recent RFC3986 reserves !, ', (, ), and \*, even though these characters have no formalized URI delimiting uses. The following function encodes a string for RFC3986-compliant URL component format. It also encodes [ and ], which are part of the IPv6 URI syntax. An RFC3986-compliant `encodeURI` implementation should not escape them, which is demonstrated in the `encodeURI()` example.

```js
function encodeRFC3986URIComponent(str) {
  return encodeURIComponent(str).replace(
    /[!'()\*]/g,
    (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
  );
}
```

### Encoding a lone surrogate throws

A `URIError` will be thrown if one attempts to encode a surrogate which is not part of a high-low pair. For example:

```js
// High-low pair OK
encodeURIComponent("\uD800\uDFFF"); // "%F0%90%8F%BF"

// Lone high-surrogate code unit throws "URIError: malformed URI sequence"
encodeURIComponent("\uD800");

// Lone high-surrogate code unit throws "URIError: malformed URI sequence"
encodeURIComponent("\uDFFF");
```

You can use `String.prototype.toWellFormed()`, which replaces lone surrogates with the Unicode replacement character (U+FFFD), to avoid this error. You can also use `String.prototype.isWellFormed()` to check if a string contains lone surrogates before passing it to `encodeURIComponent()`.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-encodeuricomponent-uricomponent |

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

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

See also
--------

* `decodeURI()`
* `encodeURI()`
* `decodeURIComponent()`


SyntaxError - JavaScript

SyntaxError
===========

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 serializable object, so it can be cloned with `structuredClone()` or copied between Workers using `postMessage()`.

`SyntaxError` is a subclass of `Error`.

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

`SyntaxError()`

Creates a new `SyntaxError` object.

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

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

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

`SyntaxError.prototype.constructor`

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

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

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

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

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

See also
--------

* `Error`


AggregateError - JavaScript

AggregateError
==============

The **`AggregateError`** object represents an error when several errors need to be wrapped in a single error. It is thrown when multiple errors need to be reported by an operation, for example by `Promise.any()`, when all promises passed to it reject.

`AggregateError` is a subclass of `Error`.

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

`AggregateError()`

Creates a new `AggregateError` object.

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

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

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

`AggregateError.prototype.constructor`

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

`AggregateError.prototype.name`

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

These properties are own properties of each `AggregateError` instance.

`errors`

An array representing the errors that were aggregated.

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

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

Examples
--------

### Catching an AggregateError

```js
Promise.any([Promise.reject(new Error("some error"))]).catch((e) => {
  console.log(e instanceof AggregateError); // true
  console.log(e.message); // "All Promises rejected"
  console.log(e.name); // "AggregateError"
  console.log(e.errors); // [ Error: "some error" ]
});
```

### Creating an AggregateError

```js
try {
  throw new AggregateError([new Error("some error")], "Hello");
} catch (e) {
  console.log(e instanceof AggregateError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "AggregateError"
  console.log(e.errors); // [ Error: "some error" ]
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-aggregate-error-objects |

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

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

See also
--------

* Polyfill of `AggregateError` in `core-js`
* `Error`
* `Promise.any`


GeneratorFunction - JavaScript

GeneratorFunction
=================

The **`GeneratorFunction`** object provides methods for generator functions. In JavaScript, every generator function is actually a `GeneratorFunction` object.

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

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

`GeneratorFunction` is a subclass of `Function`.

Try it
------

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

`GeneratorFunction()`

Creates a new `GeneratorFunction` object.

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

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

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

`GeneratorFunction.prototype.constructor`

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

`GeneratorFunction.prototype.prototype`

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

`GeneratorFunction.prototype[@@toStringTag]`

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

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

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

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

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

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

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

See also
--------

* `function*`
* `function*` expression
* `Function`
* `AsyncFunction`
* `AsyncGeneratorFunction`
* Functions


Boolean - JavaScript

Boolean
=======

The **`Boolean`** object represents a truth value: `true` or `false`.

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

### Boolean primitives and Boolean objects

Do not confuse the primitive `Boolean` values `true` and `false` with the `true` and `false` values of the `Boolean` object.

**Any** object, including a `Boolean` object whose value is `false`, evaluates to `true` when passed to a conditional statement. For example, the condition in the following `if` statement evaluates to `true`:

```js
const x = new Boolean(false);
if (x) {
  // this code is executed
}
```

This behavior does not apply to `Boolean` primitives. For example, the condition in the following `if` statement evaluates to `false`:

```js
const x = false;
if (x) {
  // this code is not executed
}
```

Do not use the `Boolean()` constructor with `new` to convert a non-boolean value to a boolean value — use `Boolean` as a function or a double NOT instead:

```js
const good = Boolean(expression); // use this
const good2 = !!expression; // or this
const bad = new Boolean(expression); // don't use this!
```

If you specify any object, including a `Boolean` object whose value is `false`, as the initial value of a `Boolean` object, the new `Boolean` object has a value of `true`.

```js
const myFalse = new Boolean(false); // initial value of false
const g = Boolean(myFalse); // initial value of true
const myString = new String("Hello"); // string object
const s = Boolean(myString); // initial value of true
```

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

### Boolean coercion

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

* Booleans are returned as-is.
* `undefined` turns into `false`.
* `null` turns into `false`.
* `0`, `-0`, and `NaN` turn into `false`; other numbers turn into `true`.
* `0n` turns into `false`; other BigInts turn into `true`.
* The empty string `""` turns into `false`; other strings turn into `true`.
* Symbols turn into `true`.
* All objects become `true`.

**Note:** A legacy behavior makes `document.all` return `false` when used as a boolean, despite it being an object. This property is legacy and non-standard and should not be used.

**Note:** Unlike other type conversions like string coercion or number coercion, boolean coercion does not attempt to convert objects to primitives.

In other words, there are only a handful of values that get coerced to `false` — these are called falsy values. All other values are called truthy values. A value's truthiness is important when used with logical operators, conditional statements, or any boolean context.

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

* Double NOT: `!!x` negates `x` twice, which converts `x` to a boolean using the same algorithm as above.
* The `Boolean()` function: `Boolean(x)` uses the same algorithm as above to convert `x`.

Note that truthiness is not the same as being loosely equal to `true` or `false`.

```js
if ([]) {
  console.log("[] is truthy");
}
if ([] == false) {
  console.log("[] == false");
}
// [] is truthy
// [] == false
```

`[]` is truthy, but it's also loosely equal to `false`. It's truthy, because all objects are truthy. However, when comparing with `false`, which is a primitive, `[]` is also converted to a primitive, which is `""` via `Array.prototype.toString()`. Comparing strings and booleans results in both being converted to numbers, and they both become `0`, so `[] == false` is `true`. In general, falsiness and `== false` differ in the following cases:

* `NaN`, `undefined`, and `null` are falsy but not loosely equal to `false`.
* `"0"` (and other string literals that are not `""` but get coerced to 0) is truthy but loosely equal to `false`.
* Objects are always truthy, but their primitive representation may be loosely equal to `false`.

Truthy values are even more unlikely to be loosely equal to `true`. All values are either truthy or falsy, but most values are loosely equal to neither `true` nor `false`.

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

`Boolean()`

Creates a new `Boolean` object.

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

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

`Boolean.prototype.constructor`

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

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

`Boolean.prototype.toString()`

Returns a string of either `true` or `false` depending upon the value of the object. Overrides the `Object.prototype.toString()` method.

`Boolean.prototype.valueOf()`

Returns the primitive value of the `Boolean` object. Overrides the `Object.prototype.valueOf()` method.

Examples
--------

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

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

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

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

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

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

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

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

See also
--------

* Boolean
* Boolean primitives
* Boolean data type on Wikipedia


WeakSet - JavaScript

WeakSet
=======

A **`WeakSet`** is a collection of garbage-collectable values, including objects and non-registered symbols. A value in the `WeakSet` may only occur once. It is unique in the `WeakSet`'s collection.

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

Values of WeakSets must be garbage-collectable. Most primitive data types can be arbitrarily created and don't have a lifetime, so they cannot be stored. Objects and non-registered symbols can be stored because they are garbage-collectable.

The main differences to the `Set` object are:

* `WeakSet`s are collections of **objects and symbols only**. They cannot contain arbitrary values of any type, as `Set`s can.
* The `WeakSet` is *weak*, meaning references to objects in a `WeakSet` are held *weakly*. If no other references to a value stored in the `WeakSet` exist, those values can be garbage collected.

**Note:** This also means that there is no list of current values stored in the collection. `WeakSets` are not enumerable.
### Use case: Detecting circular references

Functions that call themselves recursively need a way of guarding against circular data structures by tracking which objects have already been processed.

`WeakSet`s are ideal for this purpose:

```js
// Execute a callback on everything stored inside an object
function execRecursively(fn, subject, _refs = new WeakSet()) {
  // Avoid infinite recursion
  if (_refs.has(subject)) {
    return;
  }

  fn(subject);
  if (typeof subject === "object" && subject) {
    _refs.add(subject);
    for (const key in subject) {
      execRecursively(fn, subject[key], _refs);
    }
    _refs.delete(subject);
  }
}

const foo = {
  foo: "Foo",
  bar: {
    bar: "Bar",
  },
};

foo.bar.baz = foo; // Circular reference!
execRecursively((obj) => console.log(obj), foo);
```

Here, a `WeakSet` is created on the first run, and passed along with every subsequent function call (using the internal `_refs` parameter).

The number of objects or their traversal order is immaterial, so a `WeakSet` is more suitable (and performant) than a `Set` for tracking object references, especially if a very large number of objects is involved.

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

`WeakSet()`

Creates a new `WeakSet` object.

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

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

`WeakSet.prototype.constructor`

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

`WeakSet.prototype[@@toStringTag]`

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

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

`WeakSet.prototype.add()`

Appends `value` to the `WeakSet` object.

`WeakSet.prototype.delete()`

Removes `value` from the `WeakSet`. `WeakSet.prototype.has(value)` will return `false` afterwards.

`WeakSet.prototype.has()`

Returns a boolean asserting whether `value` is present in the `WeakSet` object or not.

Examples
--------

### Using the WeakSet object

```js
const ws = new WeakSet();
const foo = {};
const bar = {};

ws.add(foo);
ws.add(bar);

ws.has(foo); // true
ws.has(bar); // true

ws.delete(foo); // removes foo from the set
ws.has(foo); // false, foo has been removed
ws.has(bar); // true, bar is retained
```

Note that `foo !== bar`. While they are similar objects, *they are not **the same object***. And so they are both added to the set.

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

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

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

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

See also
--------

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