Date.UTC() - JavaScript

Date.UTC()
==========

The **`Date.UTC()`** static method accepts parameters representing the date and time components similar to the `Date` constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

Try it
------

Syntax
------

```js
Date.UTC(year)
Date.UTC(year, monthIndex)
Date.UTC(year, monthIndex, day)
Date.UTC(year, monthIndex, day, hour)
Date.UTC(year, monthIndex, day, hour, minute)
Date.UTC(year, monthIndex, day, hour, minute, second)
Date.UTC(year, monthIndex, day, hour, minute, second, millisecond)
```

### Parameters

`year`

Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the example.

`monthIndex` Optional

Integer value representing the month, beginning with `0` for January to `11` for December. Defaults to `0`.

`day` Optional

Integer value representing the day of the month. Defaults to `1`.

`hours` Optional

Integer value between `0` and `23` representing the hour of the day. Defaults to `0`.

`minutes` Optional

Integer value representing the minute segment of a time. Defaults to `0`.

`seconds` Optional

Integer value representing the second segment of a time. Defaults to `0`.

`milliseconds` Optional

Integer value representing the millisecond segment of a time. Defaults to `0`.

### Return value

A number representing the timestamp of the given date. Returns `NaN` if the date is invalid.

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

Years between `0` and `99` are converted to a year in the 20th century `(1900 + year)`. For example, `95` is converted to the year `1995`.

The `UTC()` method differs from the `Date()` constructor in three ways:

1. `Date.UTC()` uses universal time instead of the local time.
2. `Date.UTC()` returns a time value as a number instead of creating a `Date` object.
3. When passed a single number, `Date.UTC()` interprets it as a year instead of a timestamp.

If a parameter is outside of the expected range, the `UTC()` method updates the other parameters to accommodate the value. For example, if `15` is used for `monthIndex`, the year will be incremented by 1 `(year + 1)` and `3` will be used for the month.

Because `UTC()` is a static method of `Date`, you always use it as `Date.UTC()`, rather than as a method of a `Date` object you created.

Examples
--------

### Using Date.UTC()

The following statement creates a `Date` object with the arguments treated as UTC instead of local:

```js
const utcDate = new Date(Date.UTC(2018, 11, 1, 0, 0, 0));
```

### Behavior of Date.UTC() with one argument

`Date.UTC()` when passed one argument used to have inconsistent behavior, because implementations only kept the behavior consistent with the `Date()` constructor, which does not interpret a single argument as the year number. Implementations are now required to treat omitted `monthIndex` as `0`, instead of coercing it to `NaN`.

```js
Date.UTC(2017); // 1483228800000
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.utc |

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

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

See also
--------

* `Date.parse()`
* `Date`


Date.prototype.toUTCString() - JavaScript

Date.prototype.toUTCString()
============================

The **`toUTCString()`** method of `Date` instances returns a string representing this date in the RFC 7231 format, with negative years allowed. The timezone is always UTC. `toGMTString()` is an alias of this method.

Try it
------

Syntax
------

```js
toUTCString()
```

### Parameters

None.

### Return value

A string representing the given date using the UTC time zone (see description for the format). Returns `"Invalid Date"` if the date is invalid.

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

The value returned by `toUTCString()` is a string in the form `Www, dd Mmm yyyy hh:mm:ss GMT`, where:

| Format String | Description |
| --- | --- |
| `Www` | Day of week, as three letters (e.g. `Sun`, `Mon`) |
| `dd` | Day of month, as two digits with leading zero if required |
| `Mmm` | Month, as three letters (e.g. `Jan`, `Feb`) |
| `yyyy` | Year, as four or more digits with leading zeroes if required |
| `hh` | Hour, as two digits with leading zero if required |
| `mm` | Minute, as two digits with leading zero if required |
| `ss` | Seconds, as two digits with leading zero if required |

### Aliasing

JavaScript's `Date` API was inspired by Java's `java.util.Date` library (while the latter had become de facto legacy since Java 1.1 in 1997). In particular, the Java `Date` class had a method called `toGMTString` — which was poorly named, because the Greenwich Mean Time is not equivalent to the Coordinated Universal Time, while JavaScript dates always operate by UTC time. For web compatibility reasons, `toGMTString` remains as an alias to `toUTCString`, and they refer to the exact same function object. This means:

```js
Date.prototype.toGMTString.name === "toUTCString";
```

Examples
--------

### Using toUTCString()

```js
const d = new Date(0);
console.log(d.toUTCString()); // 'Thu, 01 Jan 1970 00:00:00 GMT'
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.prototype.toutcstring |

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

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

See also
--------

* `Date.prototype.toLocaleString()`
* `Date.prototype.toString()`
* `Date.prototype.toISOString()`


Date.prototype.getDate() - JavaScript

Date.prototype.getDate()
========================

The **`getDate()`** method of `Date` instances returns the day of the month for this date according to local time.

Try it
------

Syntax
------

```js
getDate()
```

### Parameters

None.

### Return value

An integer, between 1 and 31, representing the day of the month for the given date according to local time. Returns `NaN` if the date is invalid.

Examples
--------

### Using getDate()

The `day` variable has value `25`, based on the value of the `Date` object `xmas95`.

```js
const xmas95 = new Date("1995-12-25T23:15:30");
const day = xmas95.getDate();

console.log(day); // 25
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.prototype.getdate |

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

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

See also
--------

* `Date.prototype.getUTCDate()`
* `Date.prototype.getUTCDay()`
* `Date.prototype.setDate()`


Date.prototype.getMonth() - JavaScript

Date.prototype.getMonth()
=========================

The **`getMonth()`** method of `Date` instances returns the month for this date according to local time, as a zero-based value (where zero indicates the first month of the year).

Try it
------

Syntax
------

```js
getMonth()
```

### Parameters

None.

### Return value

An integer, between 0 and 11, representing the month for the given date according to local time: 0 for January, 1 for February, and so on. Returns `NaN` if the date is invalid.

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

The return value of `getMonth()` is zero-based, which is useful for indexing into arrays of months, for example:

```js
const valentines = new Date("1995-02-14");
const month = valentines.getMonth();
const monthNames = ["January", "February", "March" /\* , … \*/];

console.log(monthNames[month]); // "February"
```

However, for the purpose of internationalization, you should prefer using `Intl.DateTimeFormat` with the `options` parameter instead.

```js
const options = { month: "long" };
console.log(new Intl.DateTimeFormat("en-US", options).format(valentines));
// "February"
console.log(new Intl.DateTimeFormat("de-DE", options).format(valentines));
// "Februar"
```

Examples
--------

### Using getMonth()

The `month` variable has value `11`, based on the value of the `Date` object `xmas95`.

```js
const xmas95 = new Date("1995-12-25T23:15:30");
const month = xmas95.getMonth();

console.log(month); // 11
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.prototype.getmonth |

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

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

See also
--------

* `Date.prototype.getUTCMonth()`
* `Date.prototype.setMonth()`


Date.prototype.getSeconds() - JavaScript

Date.prototype.getSeconds()
===========================

The **`getSeconds()`** method of `Date` instances returns the seconds for this date according to local time.

Try it
------

Syntax
------

```js
getSeconds()
```

### Parameters

None.

### Return value

An integer, between 0 and 59, representing the seconds for the given date according to local time. Returns `NaN` if the date is invalid.

Examples
--------

### Using getSeconds()

The `seconds` variable has value `30`, based on the value of the `Date` object `xmas95`.

```js
const xmas95 = new Date("1995-12-25T23:15:30");
const seconds = xmas95.getSeconds();

console.log(seconds); // 30
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.prototype.getseconds |

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

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

See also
--------

* `Date.prototype.getUTCSeconds()`
* `Date.prototype.setSeconds()`


Date.prototype.toLocaleString() - JavaScript

Date.prototype.toLocaleString()
===============================

The **`toLocaleString()`** method of `Date` instances returns a string with a language-sensitive representation of this date in the local timezone. In implementations with `Intl.DateTimeFormat` API support, this method simply calls `Intl.DateTimeFormat`.

Every time `toLocaleString` is called, it has to perform a search in a big database of localization strings, which is potentially inefficient. When the method is called many times with the same arguments, it is better to create a `Intl.DateTimeFormat` object and use its `format()` method, because a `DateTimeFormat` object remembers the arguments passed to it and may decide to cache a slice of the database, so future `format` calls can search for localization strings within a more constrained context.

Try it
------

Syntax
------

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

### Parameters

The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.

In implementations that support the `Intl.DateTimeFormat` API, these parameters correspond exactly to the `Intl.DateTimeFormat()` constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.

`locales` Optional

A string with a BCP 47 language tag, or an array of such strings. Corresponds to the `locales` parameter of the `Intl.DateTimeFormat()` constructor.

In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used.

`options` Optional

An object adjusting the output format. Corresponds to the `options` parameter of the `Intl.DateTimeFormat()` constructor. If `weekday`, `year`, `month`, `day`, `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `year`, `month`, `day`, `hour`, `minute`, `second` will be set to `"numeric"`.

In implementations without `Intl.DateTimeFormat` support, this parameter is ignored.

See the `Intl.DateTimeFormat()` constructor for details on these parameters and how to use them.

### Return value

A string representing the given date according to language-specific conventions.

In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`.

**Note:** Most of the time, the formatting returned by `toLocaleString()` is consistent. However, the output may vary with time, language, and implementation — output variations are by design and allowed by the specification. You should not compare the results of `toLocaleString()` to static values.

Examples
--------

### Using toLocaleString()

Basic use of this method without specifying a `locale` returns a formatted string in the default locale and with default options.

```js
const date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));

// toLocaleString() without arguments depends on the
// implementation, the default locale, and the default time zone
console.log(date.toLocaleString());
// "12/11/2012, 7:00:00 PM" if run in en-US locale with time zone America/Los\_Angeles
```

### Checking for support for locales and options parameters

The `locales` and `options` parameters may not be supported in all implementations, because support for the internationalization API is optional, and some systems may not have the necessary data. For implementations without internationalization support, `toLocaleString()` always uses the system's locale, which may not be what you want. Because any implementation that supports the `locales` and `options` parameters must support the `Intl` API, you can check the existence of the latter for support:

```js
function toLocaleStringSupportsLocales() {
  return (
    typeof Intl === "object" &&
    !!Intl &&
    typeof Intl.DateTimeFormat === "function"
  );
}
```

### Using locales

This example shows some of the variations in localized date and time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:

```js
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// Formats below assume the local time zone of the locale;
// America/Los\_Angeles for the US

// US English uses month-day-year order and 12-hour time with AM/PM
console.log(date.toLocaleString("en-US"));
// "12/19/2012, 7:00:00 PM"

// British English uses day-month-year order and 24-hour time without AM/PM
console.log(date.toLocaleString("en-GB"));
// "20/12/2012 03:00:00"

// Korean uses year-month-day order and 12-hour time with AM/PM
console.log(date.toLocaleString("ko-KR"));
// "2012. 12. 20. 오후 12:00:00"

// Arabic in most Arabic-speaking countries uses Eastern Arabic numerals
console.log(date.toLocaleString("ar-EG"));
// "٢٠/١٢/٢٠١٢ ٥:٠٠:٠٠ ص"

// For Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(date.toLocaleString("ja-JP-u-ca-japanese"));
// "24/12/20 12:00:00"

// When requesting a language that may not be supported, such as
// Balinese, include a fallback language (in this case, Indonesian)
console.log(date.toLocaleString(["ban", "id"]));
// "20/12/2012 11.00.00"
```

### Using options

The results provided by `toLocaleString()` can be customized using the `options` parameter:

```js
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// Request a weekday along with a long date
const options = {
  weekday: "long",
  year: "numeric",
  month: "long",
  day: "numeric",
};
console.log(date.toLocaleString("de-DE", options));
// "Donnerstag, 20. Dezember 2012"

// An application may want to use UTC and make that visible
options.timeZone = "UTC";
options.timeZoneName = "short";
console.log(date.toLocaleString("en-US", options));
// "Thursday, December 20, 2012, GMT"

// Sometimes even the US needs 24-hour time
console.log(date.toLocaleString("en-US", { hour12: false }));
// "12/19/2012, 19:00:00"
```

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

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

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

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

See also
--------

* `Intl.DateTimeFormat`
* `Date.prototype.toLocaleDateString()`
* `Date.prototype.toLocaleTimeString()`
* `Date.prototype.toString()`


Date.prototype.getUTCMinutes() - JavaScript

Date.prototype.getUTCMinutes()
==============================

The **`getUTCMinutes()`** method of `Date` instances returns the minutes for this date according to universal time.

Try it
------

Syntax
------

```js
getUTCMinutes()
```

### Parameters

None.

### Return value

An integer, between 0 and 59, representing the minutes for the given date according to universal time. Returns `NaN` if the date is invalid.

Examples
--------

### Using getUTCMinutes()

The following example assigns the minutes portion of the current time to the variable `minutes`.

```js
const today = new Date();
const minutes = today.getUTCMinutes();
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.prototype.getutcminutes |

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

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

See also
--------

* `Date.prototype.getMinutes()`
* `Date.prototype.setUTCMinutes()`


Date.now() - JavaScript

Date.now()
==========

The **`Date.now()`** static method returns the number of milliseconds elapsed since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.

Try it
------

Syntax
------

```js
Date.now()
```

### Parameters

None.

### Return value

A number representing the timestamp, in milliseconds, of the current time.

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

### Reduced time precision

To offer protection against timing attacks and fingerprinting, the precision of `Date.now()` might get rounded depending on browser settings. In Firefox, the `privacy.reduceTimerPrecision` preference is enabled by default and defaults to 2ms. You can also enable `privacy.resistFingerprinting`, in which case the precision will be 100ms or the value of `privacy.resistFingerprinting.reduceTimerPrecision.microseconds`, whichever is larger.

```js
// reduced time precision (2ms) in Firefox 60
Date.now();
// 1519211809934
// 1519211810362
// 1519211811670
// …

// reduced time precision with `privacy.resistFingerprinting` enabled
Date.now();
// 1519129853500
// 1519129858900
// 1519129864400
// …
```

Examples
--------

### Measuring time elapsed

You can use `Date.now()` to get the current time in milliseconds, then subtract a previous time to find out how much time elapsed between the two calls.

```js
const start = Date.now();
doSomeLongRunningProcess();
console.log(`Time elapsed: ${Date.now() - start} ms`);
```

For more complex scenarios, you may want to use the performance API instead.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.now |

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

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

See also
--------

* Polyfill of `Date.now` in `core-js`
* `Performance.now()`
* `console.time()`
* `console.timeEnd()`


Date.prototype.getTimezoneOffset() - JavaScript

Date.prototype.getTimezoneOffset()
==================================

The **`getTimezoneOffset()`** method of `Date` instances returns the difference, in minutes, between this date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone.

Try it
------

Syntax
------

```js
getTimezoneOffset()
```

### Parameters

None.

### Return value

A number representing the difference, in minutes, between the date as evaluated in the UTC time zone and as evaluated in the local time zone. The actual local time algorithm is implementation-defined, and the return value is allowed to be zero in runtimes without appropriate data. Returns `NaN` if the date is invalid.

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

`date.getTimezoneOffset()` returns the difference, in minutes, between `date` as evaluated in the UTC time zone and as evaluated in the local time zone — that is, the time zone of the host system in which the browser is being used (if the code is run from the Web in a browser), or otherwise the host system of whatever JavaScript runtime (for example, a Node.js environment) the code is executed in.

### Negative values and positive values

The number of minutes returned by `getTimezoneOffset()` is positive if the local time zone is behind UTC, and negative if the local time zone is ahead of UTC. For example, for UTC+10, `-600` will be returned.

| Current time zone | Return value |
| --- | --- |
| UTC-8 | 480 |
| UTC | 0 |
| UTC+3 | -180 |

### Varied results in Daylight Saving Time (DST) regions

In a region that annually shifts in and out of Daylight Saving Time (DST), as `date` varies, the number of minutes returned by calling `getTimezoneOffset()` can be non-uniform.

**Note:** `getTimezoneOffset()`'s behavior will never differ based on the time when the code is run — its behavior is always consistent when running in the same region. Only the value of `date` affects the result.

In most implementations, the IANA time zone database (tzdata) is used to precisely determine the offset of the local timezone at the moment of the `date`. However, if such information is unavailable, an implementation may return zero.

Examples
--------

### Using getTimezoneOffset()

```js
// Create a Date instance for the current time
const currentLocalDate = new Date();
// Create a Date instance for 03:24 GMT-0200 on May 1st in 2016
const laborDay2016at0324GMTminus2 = new Date("2016-05-01T03:24:00-02:00");
currentLocalDate.getTimezoneOffset() ===
  laborDay2016at0324GMTminus2.getTimezoneOffset();
// true, always, in any timezone that doesn't annually shift in and out of DST
// false, sometimes, in any timezone that annually shifts in and out of DST
```

### getTimezoneOffset() and DST

In regions that use DST, the return value may change based on the time of the year `date` is in. Below is the output in a runtime in New York, where the timezone is UTC-05:00.

```js
const nyOffsetSummer = new Date("2022-02-01").getTimezoneOffset(); // 300
const nyOffsetWinter = new Date("2022-08-01").getTimezoneOffset(); // 240
```

### getTimezoneOffset() and historical data

Due to historical reasons, the timezone a region is in can be constantly changing, even disregarding DST. For example, below is the output in a runtime in Shanghai, where the timezone is UTC+08:00.

```js
const shModernOffset = new Date("2022-01-27").getTimezoneOffset(); // -480
const shHistoricalOffset = new Date("1943-01-27").getTimezoneOffset(); // -540
```

This is because during the Sino-Japanese War when Shanghai was under Japanese control, the timezone was changed to UTC+09:00 to align with Japan's (in effect, it was a "year-round DST"), and this was recorded in the IANA database.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.prototype.gettimezoneoffset |

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

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

See also
--------

* `Date`


Date.prototype.setUTCFullYear() - JavaScript

Date.prototype.setUTCFullYear()
===============================

The **`setUTCFullYear()`** method of `Date` instances changes the year for this date according to universal time.

Try it
------

Syntax
------

```js
setUTCFullYear(yearValue)
setUTCFullYear(yearValue, monthValue)
setUTCFullYear(yearValue, monthValue, dateValue)
```

### Parameters

`yearValue`

An integer representing the year. For example, 1995.

`monthValue` Optional

An integer representing the month: 0 for January, 1 for February, and so on.

`dateValue` Optional

An integer between 1 and 31 representing the day of the month. If you specify `dateValue`, you must also specify `monthValue`.

### Return value

Changes the `Date` object in place, and returns its new timestamp. If a parameter is `NaN` (or other values that get coerced to `NaN`, such as `undefined`), the date is set to Invalid Date and `NaN` is returned.

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

 If you do not specify the `monthValue` and
 `dateValue` parameters, the values returned from the
 `getUTCMonth()` and
 `getUTCDate()` methods are used.

 If a parameter you specify is outside of the expected range,
 `setUTCFullYear()` attempts to update the other parameters and the date
 information in the `Date` object accordingly. For example, if you specify 15
 for `monthValue`, the year is incremented by 1
 (`yearValue + 1`), and 3 is used for the month.

Examples
--------

### Using setUTCFullYear()

```js
const theBigDay = new Date();
theBigDay.setUTCFullYear(1997);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.prototype.setutcfullyear |

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

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

See also
--------

* `Date.prototype.getUTCFullYear()`
* `Date.prototype.setFullYear()`


Date.prototype.setUTCHours() - JavaScript

Date.prototype.setUTCHours()
============================

The **`setUTCHours()`** method of `Date` instances changes the hours, minutes, seconds, and/or milliseconds for this date according to universal time.

Try it
------

Syntax
------

```js
setUTCHours(hoursValue)
setUTCHours(hoursValue, minutesValue)
setUTCHours(hoursValue, minutesValue, secondsValue)
setUTCHours(hoursValue, minutesValue, secondsValue, msValue)
```

### Parameters

`hoursValue`

An integer between 0 and 23 representing the hours.

`minutesValue` Optional

An integer between 0 and 59 representing the minutes.

`secondsValue` Optional

An integer between 0 and 59 representing the seconds. If you specify `secondsValue`, you must also specify `minutesValue`.

`msValue` Optional

An integer between 0 and 999 representing the milliseconds. If you specify `msValue`, you must also specify `minutesValue` and `secondsValue`.

### Return value

Changes the `Date` object in place, and returns its new timestamp. If a parameter is `NaN` (or other values that get coerced to `NaN`, such as `undefined`), the date is set to Invalid Date and `NaN` is returned.

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

 If you do not specify the `minutesValue`,
 `secondsValue`, and `msValue` parameters,
 the values returned from the `getUTCMinutes()`, `getUTCSeconds()`,
 and `getUTCMilliseconds()` methods
 are used.

 If a parameter you specify is outside of the expected range, `setUTCHours()`
 attempts to update the date information in the `Date` object accordingly.
 For example, if you use 100 for `secondsValue`, the minutes will
 be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds.

Examples
--------

### Using setUTCHours()

```js
const theBigDay = new Date();
theBigDay.setUTCHours(8);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.prototype.setutchours |

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

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

See also
--------

* `Date.prototype.getUTCHours()`
* `Date.prototype.setHours()`


Date.prototype.setUTCMilliseconds() - JavaScript

Date.prototype.setUTCMilliseconds()
===================================

The **`setUTCMilliseconds()`** method of `Date` instances changes the milliseconds for this date according to universal time.

Try it
------

Syntax
------

```js
setUTCMilliseconds(millisecondsValue)
```

### Parameters

`millisecondsValue`

An integer between 0 and 999 representing the milliseconds.

### Return value

Changes the `Date` object in place, and returns its new timestamp. If `millisecondsValue` is `NaN` (or other values that get coerced to `NaN`, such as `undefined`), the date is set to Invalid Date and `NaN` is returned.

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

 If a parameter you specify is outside of the expected range,
 `setUTCMilliseconds()` attempts to update the date information in the
 `Date` object accordingly. For example, if you use 1100 for
 `millisecondsValue`, the seconds stored in the `Date`
 object will be incremented by 1, and 100 will be used for milliseconds.

Examples
--------

### Using setUTCMilliseconds()

```js
const theBigDay = new Date();
theBigDay.setUTCMilliseconds(500);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.prototype.setutcmilliseconds |

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

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

See also
--------

* `Date.prototype.getUTCMilliseconds()`
* `Date.prototype.setMilliseconds()`


Date.parse() - JavaScript

Date.parse()
============

The **`Date.parse()`** static method parses a string representation of a date, and returns the date's timestamp.

Only the date time string format is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated.

Try it
------

Syntax
------

```js
Date.parse(dateString)
```

### Parameters

`dateString`

A string in the date time string format. See the linked reference for caveats on using different formats.

### Return value

A number representing the timestamp of the given date. If `dateString` fails to be parsed as a valid date, `NaN` is returned.

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

This function is useful for setting date values based on string values, for example in conjunction with the `setTime()` method.

Because `parse()` is a static method of `Date`, you always use it as `Date.parse()`, rather than as a method of a `Date` object you created.

Examples
--------

### Using Date.parse()

The following calls all return `1546300800000`. The first will imply UTC time because it's date-only, and the others explicitly specify the UTC timezone.

```js
Date.parse("2019-01-01");
Date.parse("2019-01-01T00:00:00.000Z");
Date.parse("2019-01-01T00:00:00.000+00:00");
```

The following call, which does not specify a time zone will be set to 2019-01-01 at 00:00:00 in the local timezone of the system, because it has both date and time.

```js
Date.parse("2019-01-01T00:00:00");
```

### Non-standard date strings

**Note:** This section contains implementation-specific behavior that can be inconsistent across implementations.

Implementations usually default to the local time zone when the date string is non-standard. For consistency, we will assume that the code uses the UTC timezone.

```js
Date.parse("Jan 1, 1970"); // 0 in all implementations

Date.parse("Thu, 01 Jan 1970 00:00:00"); // 0 in all implementations

Date.parse("1970,1,1"); // 0 in Chrome and Firefox, NaN in Safari

Date.parse("02 01 1970");
// 2678400000 in Chrome and Firefox (Sun Feb 01 1970 00:00:00 GMT+0000);
// NaN in Safari

// With explicit timezone
Date.parse("Thu, 01 Jan 1970 00:00:00 GMT+0300");
// -10800000 in all implementations in all timezones

// Single number
Date.parse("0");
// 946684800000 in Chrome (Sat Jan 01 2000 00:00:00 GMT+0000);
// NaN in Firefox;
// -62167219200000 in Safari (Sat Jan 01 0000 00:00:00 GMT+0000)

// Two-digit number that may be a month
Date.parse("28"); // NaN in all implementations

// Two-digit year
Date.parse("70/01/01"); // 0 in all implementations

// Out-of-bounds date components
Date.parse("2014-25-23"); // NaN in all implementations
Date.parse("Mar 32, 2014"); // NaN in all implementations
Date.parse("2014/25/23"); // NaN in all implementations

Date.parse("2014-02-30");
// NaN in Safari and Firefox;
// 1393718400000 in Chrome (Sun Mar 02 2014 00:00:00 GMT+0000)
Date.parse("02/30/2014"); // 1393718400000 in all implementations
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.parse |

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

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

See also
--------

* `Date.UTC()`


Date.prototype.setDate() - JavaScript

Date.prototype.setDate()
========================

The **`setDate()`** method of `Date` instances changes the day of the month for this date according to local time.

Try it
------

Syntax
------

```js
setDate(dateValue)
```

### Parameters

`dateValue`

An integer representing the day of the month.

### Return value

Changes the `Date` object in place, and returns its new timestamp. If `dateValue` is `NaN` (or other values that get coerced to `NaN`, such as `undefined`), the date is set to Invalid Date and `NaN` is returned.

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

If you specify a number outside the expected range, the date information in the `Date` object is updated accordingly. For example, if the `Date` object holds June 1st, a `dateValue` of 40 changes the date to July 10th, while a `dateValue` of 0 changes the date to the last day of the previous month, May 31st.

Examples
--------

### Using setDate()

```js
const theBigDay = new Date(1962, 6, 7, 12); // noon of 1962-07-07 (7th of July 1962, month is 0-indexed)
const theBigDay2 = new Date(theBigDay).setDate(24); // 1962-07-24 (24th of July 1962)
const theBigDay3 = new Date(theBigDay).setDate(32); // 1962-08-01 (1st of August 1962)
const theBigDay4 = new Date(theBigDay).setDate(22); // 1962-07-22 (22nd of July 1962)
const theBigDay5 = new Date(theBigDay).setDate(0); // 1962-06-30 (30th of June 1962)
const theBigDay6 = new Date(theBigDay).setDate(98); // 1962-10-06 (6th of October 1962)
const theBigDay7 = new Date(theBigDay).setDate(-50); // 1962-05-11 (11th of May 1962)
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.prototype.setdate |

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

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

See also
--------

* `Date()`
* `Date.prototype.getDate()`
* `Date.prototype.setUTCDate()`


Date.prototype.getUTCDay() - JavaScript

Date.prototype.getUTCDay()
==========================

The **`getUTCDay()`** method of `Date` instances returns the day of the week for this date according to universal time, where 0 represents Sunday.

Try it
------

Syntax
------

```js
getUTCDay()
```

### Parameters

None.

### Return value

An integer corresponding to the day of the week for the given date according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Returns `NaN` if the date is invalid.

Examples
--------

### Using getUTCDay()

The following example assigns the weekday portion of the current date to the variable `weekday`.

```js
const today = new Date();
const weekday = today.getUTCDay();
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.prototype.getutcday |

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

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

See also
--------

* `Date.prototype.getUTCDate()`
* `Date.prototype.getDay()`
* `Date.prototype.setUTCDate()`


Date.prototype.toLocaleTimeString() - JavaScript

Date.prototype.toLocaleTimeString()
===================================

The **`toLocaleTimeString()`** method of `Date` instances returns a string with a language-sensitive representation of the time portion of this date in the local timezone. In implementations with `Intl.DateTimeFormat` API support, this method simply calls `Intl.DateTimeFormat`.

Every time `toLocaleTimeString` is called, it has to perform a search in a big database of localization strings, which is potentially inefficient. When the method is called many times with the same arguments, it is better to create a `Intl.DateTimeFormat` object and use its `format()` method, because a `DateTimeFormat` object remembers the arguments passed to it and may decide to cache a slice of the database, so future `format` calls can search for localization strings within a more constrained context.

Try it
------

Syntax
------

```js
toLocaleTimeString()
toLocaleTimeString(locales)
toLocaleTimeString(locales, options)
```

### Parameters

The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.

In implementations that support the `Intl.DateTimeFormat` API, these parameters correspond exactly to the `Intl.DateTimeFormat()` constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.

`locales` Optional

A string with a BCP 47 language tag, or an array of such strings. Corresponds to the `locales` parameter of the `Intl.DateTimeFormat()` constructor.

In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used.

`options` Optional

An object adjusting the output format. Corresponds to the `options` parameter of the `Intl.DateTimeFormat()` constructor. If `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `hour`, `minute`, `second` will be set to `"numeric"`.

In implementations without `Intl.DateTimeFormat` support, this parameter is ignored.

See the `Intl.DateTimeFormat()` constructor for details on these parameters and how to use them.

### Return value

A string representing the time portion of the given date according to language-specific conventions.

In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above.

**Note:** Most of the time, the formatting returned by `toLocaleTimeString()` is consistent. However, the output may vary with time, language, and implementation — output variations are by design and allowed by the specification. You should not compare the results of `toLocaleTimeString()` to static values.

Examples
--------

### Using toLocaleTimeString()

Basic use of this method without specifying a `locale` returns a formatted string in the default locale and with default options.

```js
const date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));

// toLocaleTimeString() without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(date.toLocaleTimeString());
// "7:00:00 PM" if run in en-US locale with time zone America/Los\_Angeles
```

### Checking for support for locales and options parameters

The `locales` and `options` parameters may not be supported in all implementations, because support for the internationalization API is optional, and some systems may not have the necessary data. For implementations without internationalization support, `toLocaleTimeString()` always uses the system's locale, which may not be what you want. Because any implementation that supports the `locales` and `options` parameters must support the `Intl` API, you can check the existence of the latter for support:

```js
function toLocaleTimeStringSupportsLocales() {
  return (
    typeof Intl === "object" &&
    !!Intl &&
    typeof Intl.DateTimeFormat === "function"
  );
}
```

### Using locales

This example shows some of the variations in localized time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:

```js
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// formats below assume the local time zone of the locale;
// America/Los\_Angeles for the US

// US English uses 12-hour time with AM/PM
console.log(date.toLocaleTimeString("en-US"));
// "7:00:00 PM"

// British English uses 24-hour time without AM/PM
console.log(date.toLocaleTimeString("en-GB"));
// "03:00:00"

// Korean uses 12-hour time with AM/PM
console.log(date.toLocaleTimeString("ko-KR"));
// "오후 12:00:00"

// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(date.toLocaleTimeString("ar-EG"));
// "٧:٠٠:٠٠ م"

// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(date.toLocaleTimeString(["ban", "id"]));
// "11.00.00"
```

### Using options

The results provided by `toLocaleTimeString()` can be customized using the `options` parameter:

```js
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// An application may want to use UTC and make that visible
const options = { timeZone: "UTC", timeZoneName: "short" };
console.log(date.toLocaleTimeString("en-US", options));
// "3:00:00 AM GMT"

// Sometimes even the US needs 24-hour time
console.log(date.toLocaleTimeString("en-US", { hour12: false }));
// "19:00:00"

// Show only hours and minutes, use options with the default locale - use an empty array
console.log(
  date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
);
// "20:01"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.prototype.tolocaletimestring |
| ECMAScript Internationalization API Specification # sup-date.prototype.tolocaletimestring |

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

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

See also
--------

* `Intl.DateTimeFormat`
* `Date.prototype.toLocaleDateString()`
* `Date.prototype.toLocaleString()`
* `Date.prototype.toTimeString()`
* `Date.prototype.toString()`


Date.prototype.setSeconds() - JavaScript

Date.prototype.setSeconds()
===========================

The **`setSeconds()`** method of `Date` instances changes the seconds and/or milliseconds for this date according to local time.

Try it
------

Syntax
------

```js
setSeconds(secondsValue)
setSeconds(secondsValue, msValue)
```

### Parameters

`secondsValue`

An integer between 0 and 59 representing the seconds.

`msValue` Optional

An integer between 0 and 999 representing the milliseconds.

### Return value

Changes the `Date` object in place, and returns its new timestamp. If a parameter is `NaN` (or other values that get coerced to `NaN`, such as `undefined`), the date is set to Invalid Date and `NaN` is returned.

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

 If you do not specify the `msValue` parameter, the value returned
 from the `getMilliseconds()` method is
 used.

 If a parameter you specify is outside of the expected range, `setSeconds()`
 attempts to update the date information in the `Date` object accordingly.
 For example, if you use 100 for `secondsValue`, the minutes stored
 in the `Date` object will be incremented by 1, and 40 will be used for
 seconds.

Examples
--------

### Using setSeconds()

```js
const theBigDay = new Date();
theBigDay.setSeconds(30);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.prototype.setseconds |

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

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

See also
--------

* `Date.prototype.getSeconds()`
* `Date.prototype.setUTCSeconds()`


Date.prototype.getHours() - JavaScript

Date.prototype.getHours()
=========================

The **`getHours()`** method of `Date` instances returns the hours for this date according to local time.

Try it
------

Syntax
------

```js
getHours()
```

### Parameters

None.

### Return value

An integer, between 0 and 23, representing the hours for the given date according to local time. Returns `NaN` if the date is invalid.

Examples
--------

### Using getHours()

The `hours` variable has value `23`, based on the value of the `Date` object `xmas95`.

```js
const xmas95 = new Date("1995-12-25T23:15:30");
const hours = xmas95.getHours();

console.log(hours); // 23
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.prototype.gethours |

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

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

See also
--------

* `Date.prototype.getUTCHours()`
* `Date.prototype.setHours()`


Date.prototype.getUTCMilliseconds() - JavaScript

Date.prototype.getUTCMilliseconds()
===================================

The **`getUTCMilliseconds()`** method of `Date` instances returns the milliseconds for this date according to universal time.

Try it
------

Syntax
------

```js
getUTCMilliseconds()
```

### Parameters

None.

### Return value

An integer, between 0 and 999, representing the milliseconds for the given date according to universal time. Returns `NaN` if the date is invalid.

Not to be confused with the timestamp. To get the total milliseconds since the epoch, use the `getTime()` method.

Examples
--------

### Using getUTCMilliseconds()

The following example assigns the milliseconds portion of the current time to the variable `milliseconds`.

```js
const today = new Date();
const milliseconds = today.getUTCMilliseconds();
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.prototype.getutcmilliseconds |

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

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

See also
--------

* `Date.prototype.getMilliseconds()`
* `Date.prototype.setUTCMilliseconds()`


Int32Array() constructor - JavaScript

Int32Array() constructor
========================

The **`Int32Array()`** constructor creates `Int32Array` objects. The contents are initialized to `0`.

Syntax
------

```js
new Int32Array()
new Int32Array(length)
new Int32Array(typedArray)
new Int32Array(object)

new Int32Array(buffer)
new Int32Array(buffer, byteOffset)
new Int32Array(buffer, byteOffset, length)
```

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

### Parameters

See `TypedArray`.

### Exceptions

See `TypedArray`.

Examples
--------

### Different ways to create an Int32Array

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

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

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

// From an ArrayBuffer
const buffer = new ArrayBuffer(32);
const z = new Int32Array(buffer, 4, 4);
console.log(z.byteOffset); // 4

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

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

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

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

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

See also
--------

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


GeneratorFunction() constructor - JavaScript

GeneratorFunction() constructor
===============================

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

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

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

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

Syntax
------

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

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

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

### Parameters

See `Function()`.

Examples
--------

### Creating and using a GeneratorFunction() constructor

```js
const GeneratorFunction = function\* () {}.constructor;
const g = new GeneratorFunction("a", "yield a \* 2");
const iterator = g(10);
console.log(iterator.next().value); // 20
```

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

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

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

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

See also
--------

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


Proxy() constructor - JavaScript

Proxy() constructor
===================

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

Syntax
------

```js
new Proxy(target, handler)
```

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

### Parameters

`target`

 A target object to wrap with `Proxy`. It can be any sort of object,
 including a native array, a function, or even another proxy.

`handler`

 An object whose properties are functions that define the behavior of the proxy when
 an operation is performed on it.

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

 Use the `Proxy()` constructor to create a new `Proxy` object.
 This constructor takes two mandatory arguments:

* `target` is the object for which you want to create the proxy
* `handler` is the object that defines the custom behavior of the proxy.

 An empty handler will create a proxy that behaves, in almost all respects, exactly like
 the target. By defining any of a set group of functions on the `handler`
 object, you can customize specific aspects of the proxy's behavior. For example, by
 defining `get()` you can provide a customized version of the target's
 property accessor.

### Handler functions

 This section lists all the handler functions you can define. Handler functions are
 sometimes called *traps*, because they trap calls to the underlying target
 object.

`handler.apply()`

A trap for a function call.

`handler.construct()`

A trap for the `new` operator.

`handler.defineProperty()`

A trap for `Object.defineProperty`.

`handler.deleteProperty()`

A trap for the `delete` operator.

`handler.get()`

A trap for getting property values.

`handler.getOwnPropertyDescriptor()`

A trap for `Object.getOwnPropertyDescriptor`.

`handler.getPrototypeOf()`

A trap for `Object.getPrototypeOf`.

`handler.has()`

A trap for the `in` operator.

`handler.isExtensible()`

A trap for `Object.isExtensible`.

`handler.ownKeys()`

 A trap for `Object.getOwnPropertyNames` and
 `Object.getOwnPropertySymbols`.

`handler.preventExtensions()`

A trap for `Object.preventExtensions`.

`handler.set()`

A trap for setting property values.

`handler.setPrototypeOf()`

A trap for `Object.setPrototypeOf`.

Examples
--------

### Selectively proxy property accessors

 In this example the target has two properties, `notProxied` and
 `proxied`. We define a handler that returns a different value for
 `proxied`, and lets any other accesses through to the target.

```js
const target = {
  notProxied: "original value",
  proxied: "original value",
};

const handler = {
  get(target, prop, receiver) {
    if (prop === "proxied") {
      return "replaced value";
    }
    return Reflect.get(...arguments);
  },
};

const proxy = new Proxy(target, handler);

console.log(proxy.notProxied); // "original value"
console.log(proxy.proxied); // "replaced value"
```

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

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

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

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

See also
--------

* Meta programming guide
* `Reflect`


Proxy.revocable() - JavaScript

Proxy.revocable()
=================

The **`Proxy.revocable()`** static method creates a revocable `Proxy` object.

Syntax
------

```js
Proxy.revocable(target, handler)
```

### Parameters

`target`

A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy.

`handler`

An object whose properties are functions defining the behavior of `proxy` when an operation is performed on it.

### Return value

A plain object with the following two properties:

`proxy`

A Proxy object exactly the same as one created with a `new Proxy(target, handler)` call.

`revoke`

A function with no parameters to revoke (switch off) the `proxy`.

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

The `Proxy.revocable()` factory function is the same as the `Proxy()` constructor, except that in addition to creating a proxy object, it also creates a `revoke` function that can be called to disable the proxy. The proxy object and the `revoke` function are wrapped in a plain object.

The `revoke` function does not take any parameters, nor does it rely on the `this` value. The created `proxy` object is attached to the `revoke` function as a private property that the `revoke` function accesses on itself when called (the existence of the private property is not observable from the outside, but it has implications on how garbage collection happens). The `proxy` object is *not* captured within the closure of the `revoke` function (which will make garbage collection of `proxy` impossible if `revoke` is still alive).

After the `revoke()` function gets called, the proxy becomes unusable: any trap to a handler throws a `TypeError`. Once a proxy is revoked, it remains revoked, and calling `revoke()` again has no effect — in fact, the call to `revoke()` detaches the `proxy` object from the `revoke` function, so the `revoke` function will not be able to access the proxy again at all. If the proxy is not referenced elsewhere, it will then be eligible for garbage collection. The `revoke` function also detaches `target` and `handler` from the `proxy`, so if `target` is not referenced elsewhere, it will also be eligible for garbage collection, even when its proxy is still alive, since there's no longer a way to meaningfully interact with the target object.

Letting users interact with an object through a revocable proxy allows you to control the lifetime of the object exposed to the user — you can make the object garbage-collectable even when the user is still holding a reference to its proxy.

Examples
--------

### Using Proxy.revocable()

```js
const revocable = Proxy.revocable(
  {},
  {
    get(target, name) {
      return `[[${name}]]`;
    },
  },
);
const proxy = revocable.proxy;
console.log(proxy.foo); // "[[foo]]"

revocable.revoke();

console.log(proxy.foo); // TypeError is thrown
proxy.foo = 1; // TypeError again
delete proxy.foo; // still TypeError
typeof proxy; // "object", typeof doesn't trigger any trap
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-proxy.revocable |

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

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

See also
--------

* `Proxy`


handler.getPrototypeOf() - JavaScript

handler.getPrototypeOf()
========================

The **`handler.getPrototypeOf()`** method is a trap for the `[[GetPrototypeOf]]` object internal method, which is used by operations such as `Object.getPrototypeOf()`.

Try it
------

Syntax
------

```js
new Proxy(obj, {
  getPrototypeOf(target) {
    // …
  }
});
```

### Parameters

 The following parameter is passed to the `getPrototypeOf()` method.
 `this` is bound to the handler.

`target`

The target object.

### Return value

The `getPrototypeOf()` method must return an object or `null`.

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

### Interceptions

This trap can intercept these operations:

* `Object.getPrototypeOf()`
* `Reflect.getPrototypeOf()`
* `__proto__`
* `Object.prototype.isPrototypeOf()`
* `instanceof`

Or any other operation that invokes the `[[GetPrototypeOf]]` internal method.

### Invariants

If the following invariants are violated, the trap throws a `TypeError` when invoked.

* `getPrototypeOf()` method must return an object or `null`.
* If `target` is not extensible,
 `Object.getPrototypeOf(proxy)` method must return the same
 value as `Object.getPrototypeOf(target)`.
Examples
--------

### Basic usage

```js
const obj = {};
const proto = {};
const handler = {
  getPrototypeOf(target) {
    console.log(target === obj); // true
    console.log(this === handler); // true
    return proto;
  },
};

const p = new Proxy(obj, handler);
console.log(Object.getPrototypeOf(p) === proto); // true
```

### Five ways to trigger the getPrototypeOf trap

```js
const obj = {};
const p = new Proxy(obj, {
  getPrototypeOf(target) {
    return Array.prototype;
  },
});
console.log(
  Object.getPrototypeOf(p) === Array.prototype, // true
  Reflect.getPrototypeOf(p) === Array.prototype, // true
  p.__proto__ === Array.prototype, // true
  Array.prototype.isPrototypeOf(p), // true
  p instanceof Array, // true
);
```

### Two kinds of exceptions

```js
const obj = {};
const p = new Proxy(obj, {
  getPrototypeOf(target) {
    return "foo";
  },
});
Object.getPrototypeOf(p); // TypeError: "foo" is not an object or null

const obj2 = Object.preventExtensions({});
const p2 = new Proxy(obj2, {
  getPrototypeOf(target) {
    return {};
  },
});
Object.getPrototypeOf(p2); // TypeError: expected same prototype value
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-getprototypeof |

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

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

See also
--------

* `Proxy`
* `Proxy()` constructor
* `Object.getPrototypeOf()`
* `Reflect.getPrototypeOf()`


handler.deleteProperty() - JavaScript

handler.deleteProperty()
========================

The **`handler.deleteProperty()`** method is a trap for the `[[Delete]]` object internal method, which is used by operations such as the `delete` operator.

Try it
------

Syntax
------

```js
new Proxy(target, {
  deleteProperty(target, property) {
  }
});
```

### Parameters

 The following parameters are passed to the `deleteProperty()` method.
 `this` is bound to the handler.

`target`

The target object.

`property`

The name or `Symbol` of the property to delete.

### Return value

 The `deleteProperty()` method must return a boolean value indicating
 whether or not the property has been successfully deleted.

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

### Interceptions

This trap can intercept these operations:

* The `delete` operator: `delete proxy[foo]` and
 `delete proxy.foo`
* `Reflect.deleteProperty()`

Or any other operation that invokes the `[[Delete]]` internal method.

### Invariants

If the following invariants are violated, the trap throws a `TypeError` when invoked.

* A property cannot be deleted, if it exists as a non-configurable own property of the
 target object.
Examples
--------

### Trapping the delete operator

The following code traps the `delete` operator.

```js
const p = new Proxy(
  {},
  {
    deleteProperty(target, prop) {
      if (!(prop in target)) {
        console.log(`property not found: ${prop}`);
        return false;
      }
      delete target[prop];
      console.log(`property removed: ${prop}`);
      return true;
    },
  },
);

p.a = 10;
console.log("a" in p); // true

const result1 = delete p.a; // "property removed: a"
console.log(result1); // true
console.log("a" in p); // false

const result2 = delete p.a; // "property not found: a"
console.log(result2); // false
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-delete-p |

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

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

See also
--------

* `Proxy`
* `Proxy()` constructor
* `delete`
* `Reflect.deleteProperty()`


handler.getOwnPropertyDescriptor() - JavaScript

handler.getOwnPropertyDescriptor()
==================================

The **`handler.getOwnPropertyDescriptor()`** method is a trap for the `[[GetOwnProperty]]` object internal method, which is used by operations such as `Object.getOwnPropertyDescriptor()`.

Try it
------

Syntax
------

```js
new Proxy(target, {
  getOwnPropertyDescriptor(target, prop) {
  }
});
```

### Parameters

The following parameters are passed to the `getOwnPropertyDescriptor()` method. `this` is bound to the handler.

`target`

The target object.

`prop`

The name of the property whose description should be retrieved.

### Return value

The `getOwnPropertyDescriptor()` method must return an object or `undefined`.

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

### Interceptions

This trap can intercept these operations:

* `Object.getOwnPropertyDescriptor()`
* `Reflect.getOwnPropertyDescriptor()`

Or any other operation that invokes the `[[GetOwnProperty]]` internal method.

### Invariants

If the following invariants are violated, the trap throws a `TypeError` when invoked.

* `getOwnPropertyDescriptor()` must return an object or `undefined`.
* A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.
* A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible.
* A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible.
* A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object.
* The result of `Object.getOwnPropertyDescriptor(target)` can be applied to the target object using `Object.defineProperty()` and will not throw an exception.
Examples
--------

### Trapping of getOwnPropertyDescriptor

The following code traps `Object.getOwnPropertyDescriptor()`.

```js
const p = new Proxy(
  { a: 20 },
  {
    getOwnPropertyDescriptor(target, prop) {
      console.log(`called: ${prop}`);
      return { configurable: true, enumerable: true, value: 10 };
    },
  },
);

console.log(Object.getOwnPropertyDescriptor(p, "a").value);
// "called: a"
// 10
```

The following code violates an invariant.

```js
const obj = { a: 10 };
Object.preventExtensions(obj);
const p = new Proxy(obj, {
  getOwnPropertyDescriptor(target, prop) {
    return undefined;
  },
});

Object.getOwnPropertyDescriptor(p, "a"); // TypeError is thrown
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p |

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

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

See also
--------

* `Proxy`
* `Proxy()` constructor
* `Object.getOwnPropertyDescriptor()`
* `Reflect.getOwnPropertyDescriptor()`


handler.set() - JavaScript

handler.set()
=============

The **`handler.set()`** method is a trap for the `[[Set]]` object internal method, which is used by operations such as using property accessors to set a property's value.

Try it
------

Syntax
------

```js
new Proxy(target, {
  set(target, property, value, receiver) {
  }
});
```

### Parameters

 The following parameters are passed to the `set()` method. `this`
 is bound to the handler.

`target`

The target object.

`property`

The name or `Symbol` of the property to set.

`value`

The new value of the property to set.

`receiver`

 The object to which the assignment was originally directed. This is usually the
 proxy itself. But a `set()` handler can also be called indirectly, via
 the prototype chain or various other ways.

 For example, suppose a script does
 `obj.name = "jen"`, and `obj` is not a
 proxy, and has no own property `.name`, but it has a proxy on its
 prototype chain. That proxy's `set()` handler will be called, and
 `obj` will be passed as the receiver.

### Return value

The `set()` method should return a boolean value.

* Return `true` to indicate that assignment succeeded.
* If the `set()` method returns `false`, and the assignment
 happened in strict-mode code, a `TypeError` will be thrown.
Description
-----------

### Interceptions

This trap can intercept these operations:

* Property assignment: `proxy[foo] = bar` and `proxy.foo = bar`
* `Reflect.set()`

Or any other operation that invokes the `[[Set]]` internal method.

### Invariants

If the following invariants are violated, the trap throws a `TypeError` when invoked.

* Cannot change the value of a property to be different from the value of the
 corresponding target object property if the corresponding target object property is a
 non-writable, non-configurable data property.
* Cannot set the value of a property if the corresponding target object property is a
 non-configurable accessor property that has `undefined` as its
 `[[Set]]` attribute.
* In strict mode, a `false` return value from the `set()`
 handler will throw a `TypeError` exception.
Examples
--------

### Trap setting of a property value

The following code traps setting a property value.

```js
const p = new Proxy(
  {},
  {
    set(target, prop, value, receiver) {
      target[prop] = value;
      console.log(`property set: ${prop} = ${value}`);
      return true;
    },
  },
);

console.log("a" in p); // false

p.a = 10; // "property set: a = 10"
console.log("a" in p); // true
console.log(p.a); // 10
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-set-p-v-receiver |

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

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

See also
--------

* `Proxy`
* `Proxy()` constructor
* `Reflect.set()`


handler.preventExtensions() - JavaScript

handler.preventExtensions()
===========================

The **`handler.preventExtensions()`** method is a trap for the `[[PreventExtensions]]` object internal method, which is used by operations such as `Object.preventExtensions()`.

Try it
------

Syntax
------

```js
new Proxy(target, {
  preventExtensions(target) {
  }
});
```

### Parameters

The following parameter is passed to the `preventExtensions()` method. `this` is bound to the handler.

`target`

The target object.

### Return value

The `preventExtensions()` method must return a boolean value.

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

### Interceptions

This trap can intercept these operations:

* `Object.preventExtensions()`
* `Reflect.preventExtensions()`
* `Object.seal()`
* `Object.freeze()`

Or any other operation that invokes the `[[PreventExtensions]]` internal method.

### Invariants

If the following invariants are violated, the trap throws a `TypeError` when invoked.

* `Object.preventExtensions(proxy)` only returns `true` if `Object.isExtensible(proxy)` is `false`.
Examples
--------

### Trapping of preventExtensions

The following code traps `Object.preventExtensions()`.

```js
const p = new Proxy(
  {},
  {
    preventExtensions(target) {
      console.log("called");
      Object.preventExtensions(target);
      return true;
    },
  },
);

console.log(Object.preventExtensions(p));
// "called"
// false
```

The following code violates the invariant.

```js
const p = new Proxy(
  {},
  {
    preventExtensions(target) {
      return true;
    },
  },
);

Object.preventExtensions(p); // TypeError is thrown
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-preventextensions |

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

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

See also
--------

* `Proxy`
* `Proxy()` constructor
* `Object.preventExtensions()`
* `Reflect.preventExtensions()`


handler.defineProperty() - JavaScript

handler.defineProperty()
========================

The **`handler.defineProperty()`** method is a trap for the `[[DefineOwnProperty]]` object internal method, which is used by operations such as `Object.defineProperty()`.

Try it
------

Syntax
------

```js
new Proxy(target, {
  defineProperty(target, property, descriptor) {
  }
});
```

### Parameters

 The following parameters are passed to the `defineProperty()` method.
 `this` is bound to the handler.

`target`

The target object.

`property`

 The name or `Symbol` of the property whose description is to be
 retrieved.

`descriptor`

The descriptor for the property being defined or modified.

### Return value

 The `defineProperty()` method must return a `Boolean` indicating
 whether or not the property has been successfully defined.

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

### Interceptions

This trap can intercept these operations:

* `Object.defineProperty()`, `Object.defineProperties()`
* `Reflect.defineProperty()`

Or any other operation that invokes the `[[DefineOwnProperty]]` internal method.

### Invariants

If the following invariants are violated, the trap throws a `TypeError` when invoked.

* A property cannot be added, if the target object is not extensible.
* A property cannot be added as or modified to be non-configurable, if it does not
 exists as a non-configurable own property of the target object.
* A property may not be non-configurable, if a corresponding configurable property of
 the target object exists.
* If a property has a corresponding target object property then
 `Object.defineProperty(target, prop, descriptor)`
 will not throw an exception.
* In strict mode, a `false` return value from the
 `defineProperty()` handler will throw a `TypeError` exception.
Examples
--------

### Trapping of defineProperty

The following code traps `Object.defineProperty()`.

```js
const p = new Proxy(
  {},
  {
    defineProperty(target, prop, descriptor) {
      console.log(`called: ${prop}`);
      return true;
    },
  },
);

const desc = { configurable: true, enumerable: true, value: 10 };
Object.defineProperty(p, "a", desc); // "called: a"
```

 When calling `Object.defineProperty()` or
 `Reflect.defineProperty()`, the `descriptor` passed to
 `defineProperty()` trap has one restriction—only following properties are
 usable (non-standard properties will be ignored):

* `enumerable`
* `configurable`
* `writable`
* `value`
* `get`
* `set`

```js
const p = new Proxy(
  {},
  {
    defineProperty(target, prop, descriptor) {
      console.log(descriptor);
      return Reflect.defineProperty(target, prop, descriptor);
    },
  },
);

Object.defineProperty(p, "name", {
  value: "proxy",
  type: "custom",
}); // { value: 'proxy' }
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc |

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

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

See also
--------

* `Proxy`
* `Proxy()` constructor
* `Object.defineProperty()`
* `Reflect.defineProperty()`


handler.get() - JavaScript

handler.get()
=============

The **`handler.get()`** method is a trap for the `[[Get]]` object internal method, which is used by operations such as property accessors.

Try it
------

Syntax
------

```js
new Proxy(target, {
  get(target, property, receiver) {
  }
});
```

### Parameters

 The following parameters are passed to the `get()` method. `this`
 is bound to the handler.

`target`

The target object.

`property`

The name or `Symbol` of the property to get.

`receiver`

Either the proxy or an object that inherits from the proxy.

### Return value

The `get()` method can return any value.

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

### Interceptions

This trap can intercept these operations:

* Property access: `proxy[foo]` and `proxy.bar`
* `Reflect.get()`

Or any other operation that invokes the `[[Get]]` internal method.

### Invariants

If the following invariants are violated, the trap throws a `TypeError` when invoked.

* The value reported for a property must be the same as the value of the corresponding
 target object property if the target object property is a non-writable,
 non-configurable own data property.
* The value reported for a property must be undefined if the corresponding target
 object property is a non-configurable own accessor property that has
 `undefined` as its `[[Get]]` attribute.
Examples
--------

### Trap for getting a property value

The following code traps getting a property value.

```js
const p = new Proxy(
  {},
  {
    get(target, property, receiver) {
      console.log(`called: ${property}`);
      return 10;
    },
  },
);

console.log(p.a);
// "called: a"
// 10
```

The following code violates an invariant.

```js
const obj = {};
Object.defineProperty(obj, "a", {
  configurable: false,
  enumerable: false,
  value: 10,
  writable: false,
});

const p = new Proxy(obj, {
  get(target, property) {
    return 20;
  },
});

p.a; // TypeError is thrown
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver |

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

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

See also
--------

* `Proxy`
* `Proxy()` constructor
* `Reflect.get()`


handler.isExtensible() - JavaScript

handler.isExtensible()
======================

The **`handler.isExtensible()`** method is a trap for the `[[IsExtensible]]` object internal method, which is used by operations such as `Object.isExtensible()`.

Try it
------

Syntax
------

```js
new Proxy(target, {
  isExtensible(target) {
  }
});
```

### Parameters

 The following parameter is passed to the `isExtensible()` method.
 `this` is bound to the handler.

`target`

The target object.

### Return value

The `isExtensible()` method must return a boolean value.

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

### Interceptions

This trap can intercept these operations:

* `Object.isExtensible()`
* `Reflect.isExtensible()`

Or any other operation that invokes the `[[IsExtensible]]` internal method.

### Invariants

If the following invariants are violated, the trap throws a `TypeError` when invoked.

* `Object.isExtensible(proxy)` must return the same value as
 `Object.isExtensible(target)`.
Examples
--------

### Trapping of isExtensible

The following code traps `Object.isExtensible()`.

```js
const p = new Proxy(
  {},
  {
    isExtensible(target) {
      console.log("called");
      return true;
    },
  },
);

console.log(Object.isExtensible(p));
// "called"
// true
```

The following code violates the invariant.

```js
const p = new Proxy(
  {},
  {
    isExtensible(target) {
      return false;
    },
  },
);

Object.isExtensible(p); // TypeError is thrown
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-isextensible |

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

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

See also
--------

* `Proxy`
* `Proxy()` constructor
* `Object.isExtensible()`
* `Reflect.isExtensible()`
* `Reflect.preventExtensions()`


handler.ownKeys() - JavaScript

handler.ownKeys()
=================

The **`handler.ownKeys()`** method is a trap for the `[[OwnPropertyKeys]]` object internal method, which is used by operations such as `Object.keys()`, `Reflect.ownKeys()`, etc.

Try it
------

Syntax
------

```js
new Proxy(target, {
  ownKeys(target) {
  }
});
```

### Parameters

 The following parameter is passed to the `ownKeys()` method.
 `this` is bound to the handler.

`target`

The target object.

### Return value

The `ownKeys()` method must return an enumerable object.

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

### Interceptions

This trap can intercept these operations:

* `Object.getOwnPropertyNames()`
* `Object.getOwnPropertySymbols()`
* `Object.keys()`
* `Reflect.ownKeys()`

Or any other operation that invokes the `[[OwnPropertyKeys]]` internal method.

### Invariants

If the following invariants are violated, the trap throws a `TypeError` when invoked.

* The result of `ownKeys()` must be an array.
* The type of each array element is either a `String` or a
 `Symbol`.
* The result List must contain the keys of all non-configurable own properties of the
 target object.
* If the target object is not extensible, then the result List must contain all the
 keys of the own properties of the target object and no other values.
Examples
--------

### Trapping of getOwnPropertyNames

The following code traps `Object.getOwnPropertyNames()`.

```js
const p = new Proxy(
  {},
  {
    ownKeys(target) {
      console.log("called");
      return ["a", "b", "c"];
    },
  },
);

console.log(Object.getOwnPropertyNames(p));
// "called"
// [ 'a', 'b', 'c' ]
```

The following code violates an invariant.

```js
const obj = {};
Object.defineProperty(obj, "a", {
  configurable: false,
  enumerable: true,
  value: 10,
});

const p = new Proxy(obj, {
  ownKeys(target) {
    return [123, 12.5, true, false, undefined, null, {}, []];
  },
});

console.log(Object.getOwnPropertyNames(p));

// TypeError: proxy [[OwnPropertyKeys]] must return an array
// with only string and symbol elements
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys |

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

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

See also
--------

* `Proxy`
* `Proxy()` constructor
* `Object.getOwnPropertyNames()`
* `Reflect.ownKeys()`


handler.setPrototypeOf() - JavaScript

handler.setPrototypeOf()
========================

The **`handler.setPrototypeOf()`** method is a trap for the `[[SetPrototypeOf]]` object internal method, which is used by operations such as `Object.setPrototypeOf()`.

Try it
------

Syntax
------

```js
new Proxy(target, {
  setPrototypeOf(target, prototype) {
  }
});
```

### Parameters

 The following parameters are passed to the `setPrototypeOf()` method.
 `this` is bound to the handler.

`target`

The target object.

`prototype`

The object's new prototype or `null`.

### Return value

 The `setPrototypeOf()` method returns `true` if the
 `[[Prototype]]` was successfully changed, otherwise `false`.

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

### Interceptions

This trap can intercept these operations:

* `Object.setPrototypeOf()`
* `Reflect.setPrototypeOf()`

Or any other operation that invokes the `[[SetPrototypeOf]]` internal method.

### Invariants

If the following invariants are violated, the trap throws a `TypeError` when invoked.

* If `target` is not extensible, the `prototype`
 parameter must be the same value as
 `Object.getPrototypeOf(target)`.
Examples
--------

 If you want to disallow setting a new prototype for your object, your handler's
 `setPrototypeOf()` method can either return `false`, or it can
 throw an exception.

### Approach 1: Returning false

 This approach means that any mutating operation that throws an exception on failure to
 mutate, must create the exception itself.

 For example, `Object.setPrototypeOf()` will create and throw a
 `TypeError` itself. If the mutation is performed by an operation that
 *doesn't* ordinarily throw in case of failure, such as
 `Reflect.setPrototypeOf()`, no exception will be thrown.

```js
const handlerReturnsFalse = {
  setPrototypeOf(target, newProto) {
    return false;
  },
};

const newProto = {},
  target = {};

const p1 = new Proxy(target, handlerReturnsFalse);
Object.setPrototypeOf(p1, newProto); // throws a TypeError
Reflect.setPrototypeOf(p1, newProto); // returns false
```

### Approach 2: Throwing an Exception

 The latter approach will cause *any* operation that attempts to mutate, to
 throw. This approach is best if you want even non-throwing operations to throw on
 failure, or you want to throw a custom exception value.

```js
const handlerThrows = {
  setPrototypeOf(target, newProto) {
    throw new Error("custom error");
  },
};

const newProto = {},
  target = {};

const p2 = new Proxy(target, handlerThrows);
Object.setPrototypeOf(p2, newProto); // throws new Error("custom error")
Reflect.setPrototypeOf(p2, newProto); // throws new Error("custom error")
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-setprototypeof-v |

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

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

See also
--------

* `Proxy`
* `Proxy()` constructor
* `Object.setPrototypeOf()`
* `Reflect.setPrototypeOf()`


handler.has() - JavaScript

handler.has()
=============

The **`handler.has()`** method is a trap for the `[[HasProperty]]` object internal method, which is used by operations such as the `in` operator.

Try it
------

Syntax
------

```js
new Proxy(target, {
  has(target, prop) {
  }
});
```

### Parameters

 The following parameters are passed to `has()` method. `this` is
 bound to the handler.

`target`

The target object.

`prop`

The name or `Symbol` of the property to check for existence.

### Return value

The `has()` method must return a boolean value.

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

### Interceptions

This trap can intercept these operations:

* The `in` operator: `foo in proxy`
* `with` check: `with(proxy) { (foo); }`
* `Reflect.has()`

Or any other operation that invokes the `[[HasProperty]]` internal method.

### Invariants

If the following invariants are violated, the trap throws a `TypeError` when invoked.

* A property cannot be reported as non-existent, if it exists as a non-configurable
 own property of the target object.
* A property cannot be reported as non-existent, if it exists as an own property of
 the target object and the target object is not extensible.
Examples
--------

### Trapping the in operator

The following code traps the `in` operator.

```js
const p = new Proxy(
  {},
  {
    has(target, prop) {
      console.log(`called: ${prop}`);
      return true;
    },
  },
);

console.log("a" in p);
// "called: a"
// true
```

The following code violates an invariant.

```js
const obj = { a: 10 };
Object.preventExtensions(obj);

const p = new Proxy(obj, {
  has(target, prop) {
    return false;
  },
});

"a" in p; // TypeError is thrown
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-hasproperty-p |

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

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

See also
--------

* `Proxy`
* `Proxy()` constructor
* `in`
* `Reflect.has()`


handler.apply() - JavaScript

handler.apply()
===============

The **`handler.apply()`** method is a trap for the `[[Call]]` object internal method, which is used by operations such as function calls.

Try it
------

Syntax
------

```js
new Proxy(target, {
  apply(target, thisArg, argumentsList) {
  }
});
```

### Parameters

The following parameters are passed to the `apply()` method. `this` is bound to the handler.

`target`

The target callable object.

`thisArg`

The `this` argument for the call.

`argumentsList`

The list of arguments for the call.

### Return value

The `apply()` method can return any value.

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

### Interceptions

This trap can intercept these operations:

* Function call: `proxy(...args)`
* `Function.prototype.apply()` and `Function.prototype.call()`
* `Reflect.apply()`

Or any other operation that invokes the `[[Call]]` internal method.

### Invariants

If the following invariants are violated, the trap throws a `TypeError` when invoked.

* The `target` must be a callable itself. That is, it must be a function object.
Examples
--------

### Trapping a function call

The following code traps a function call.

```js
const p = new Proxy(function () {}, {
  apply(target, thisArg, argumentsList) {
    console.log(`called: ${argumentsList}`);
    return argumentsList[0] + argumentsList[1] + argumentsList[2];
  },
});

console.log(p(1, 2, 3)); // "called: 1,2,3"
// 6
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist |

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

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

See also
--------

* `Proxy`
* `Proxy()` constructor
* `Function.prototype.apply()`
* `Function.prototype.call()`
* `Reflect.apply()`


handler.construct() - JavaScript

handler.construct()
===================

The **`handler.construct()`** method is a trap for the `[[Construct]]` object internal method, which is used by operations such as the `new` operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself be a valid constructor.

Try it
------

Syntax
------

```js
new Proxy(target, {
  construct(target, argumentsList, newTarget) {
  }
});
```

### Parameters

The following parameters are passed to the `construct()` method. `this` is bound to the handler.

`target`

The target object.

`argumentsList`

The list of arguments for the constructor.

`newTarget`

The constructor that was originally called.

### Return value

The `construct` method must return an object.

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

### Interceptions

This trap can intercept these operations:

* The `new` operator: `new myFunction(...args)`
* `Reflect.construct()`

Or any other operation that invokes the `[[Construct]]` internal method.

### Invariants

If the following invariants are violated, the trap throws a `TypeError` when invoked.

* The result must be an `Object`.
Examples
--------

### Trapping the new operator

The following code traps the `new` operator.

```js
const p = new Proxy(function () {}, {
  construct(target, argumentsList, newTarget) {
    console.log(`called: ${argumentsList}`);
    return { value: argumentsList[0] \* 10 };
  },
});

console.log(new p(1).value); // "called: 1"
// 10
```

The following code violates the invariant.

```js
const p = new Proxy(function () {}, {
  construct(target, argumentsList, newTarget) {
    return 1;
  },
});

new p(); // TypeError is thrown
```

The following code improperly initializes the proxy. The `target` in Proxy initialization must itself be a valid constructor for the `new` operator.

```js
const p = new Proxy(
  {},
  {
    construct(target, argumentsList, newTarget) {
      return {};
    },
  },
);

new p(); // TypeError is thrown, "p" is not a constructor
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-construct-argumentslist-newtarget |

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

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

See also
--------

* `Proxy`
* `Proxy()` constructor
* `new`
* `Reflect.construct()`


WeakSet() constructor - JavaScript

WeakSet() constructor
=====================

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

Syntax
------

```js
new WeakSet()
new WeakSet(iterable)
```

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

### Parameters

`iterable` Optional

If an iterable object is passed, all of its elements will be added to the new `WeakSet`. `null` is treated as `undefined`.

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

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


WeakSet.prototype.delete() - JavaScript

WeakSet.prototype.delete()
==========================

The **`delete()`** method of `WeakSet` instances removes the specified element from this `WeakSet`.

Try it
------

Syntax
------

```js
weakSetInstance.delete(value)
```

### Parameters

`value`

The value to remove from the `WeakSet` object.

### Return value

`true` if an element in the `WeakSet` object has been removed successfully. `false` if the `value` is not found in the `WeakSet`. Always returns `false` if `value` is not an object or a non-registered symbol.

Examples
--------

### Using the delete() method

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

ws.add(window);

ws.delete(obj); // Returns false. No obj found to be deleted.
ws.delete(window); // Returns true. Successfully removed.

ws.has(window); // Returns false. The window is no longer present in the WeakSet.
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-weakset.prototype.delete |

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

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

See also
--------

* `WeakSet`
* `WeakSet.prototype.add()`
* `WeakSet.prototype.has()`


WeakSet.prototype.add() - JavaScript

WeakSet.prototype.add()
=======================

The **`add()`** method of `WeakSet` instances appends a new object to the end of this `WeakSet`.

Try it
------

Syntax
------

```js
add(value)
```

### Parameters

`value`

Must be either an object or a non-registered symbol. The value to add to the `WeakSet` collection.

### Return value

The `WeakSet` object.

### Exceptions

`TypeError`

Thrown if `value` is not an object or a non-registered symbol.

Examples
--------

### Using add

```js
const ws = new WeakSet();

ws.add(window); // add the window object to the WeakSet

ws.has(window); // true

// WeakSet only takes objects as arguments
ws.add(1);
// results in "TypeError: Invalid value used in weak set" in Chrome
// and "TypeError: 1 is not a non-null object" in Firefox
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-weakset.prototype.add |

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

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

See also
--------

* `WeakSet`
* `WeakSet.prototype.delete()`
* `WeakSet.prototype.has()`


WeakSet.prototype.has() - JavaScript

WeakSet.prototype.has()
=======================

 The **`has()`** method of `WeakSet` instances returns a boolean indicating whether an
 object exists in this `WeakSet` or not.

Try it
------

Syntax
------

```js
has(value)
```

### Parameters

`value`

The value to test for presence in the `WeakSet`.

### Return value

Returns `true` if an element with the specified value exists in the `WeakSet` object; otherwise `false`. Always returns `false` if `value` is not an object or a non-registered symbol.

Examples
--------

### Using the `has()` method

```js
const ws = new WeakSet();
const obj = {};
ws.add(window);

ws.has(window); // returns true
ws.has(obj); // returns false

// Storing a non-registered symbol
const sym = Symbol("foo");
ws.add(sym);
ws.add(Symbol.iterator);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-weakset.prototype.has |

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

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

See also
--------

* `WeakSet`
* `WeakSet.prototype.add()`
* `WeakSet.prototype.delete()`


BigUint64Array() constructor - JavaScript

BigUint64Array() constructor
============================

The **`BigUint64Array()`** constructor creates `BigUint64Array` objects. The contents are initialized to `0n`.

Syntax
------

```js
new BigUint64Array()
new BigUint64Array(length)
new BigUint64Array(typedArray)
new BigUint64Array(object)

new BigUint64Array(buffer)
new BigUint64Array(buffer, byteOffset)
new BigUint64Array(buffer, byteOffset, length)
```

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

### Parameters

See `TypedArray`.

### Exceptions

See `TypedArray`.

Examples
--------

### Different ways to create a BigUint64Array

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

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

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

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

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

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

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

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`


Float32Array() constructor - JavaScript

Float32Array() constructor
==========================

The **`Float32Array()`** constructor creates `Float32Array` objects. The contents are initialized to `0`.

Syntax
------

```js
new Float32Array()
new Float32Array(length)
new Float32Array(typedArray)
new Float32Array(object)

new Float32Array(buffer)
new Float32Array(buffer, byteOffset)
new Float32Array(buffer, byteOffset, length)
```

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

### Parameters

See `TypedArray`.

### Exceptions

See `TypedArray`.

Examples
--------

### Different ways to create a Float32Array

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

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

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

// From an ArrayBuffer
const buffer = new ArrayBuffer(32);
const z = new Float32Array(buffer, 4, 4);
console.log(z.byteOffset); // 4

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

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

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

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

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

See also
--------

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