String() constructor - JavaScript

String() constructor
====================

The **`String()`** constructor creates `String` objects. When called as a function, it returns primitive values of type String.

Syntax
------

```js
new String(thing)
String(thing)
```

**Note:** `String()` can be called with or without `new`, but with different effects. See Return value.

### Parameters

`thing`

Anything to be converted to a string.

### Return value

When `String` is called as a constructor (with `new`), it creates a `String` object, which is **not** a primitive.

When `String` is called as a function, it coerces the parameter to a string primitive. Symbol values would be converted to `"Symbol(description)"`, where `description` is the description of the Symbol, instead of throwing.

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

Examples
--------

### String constructor and String function

String function and String constructor produce different results:

```js
const a = new String("Hello world"); // a === "Hello world" is false
const b = String("Hello world"); // b === "Hello world" is true
a instanceof String; // is true
b instanceof String; // is false
typeof a; // "object"
typeof b; // "string"
```

 Here, the function produces a string (the primitive type) as promised.
 However, the constructor produces an instance of the type String (an object wrapper) and
 that's why you rarely want to use the String constructor at all.

### Using String() to stringify a symbol

`String()` is the only case where a symbol can be converted to a string without throwing, because it's very explicit.

```js
const sym = Symbol("example");
`${sym}`; // TypeError: Cannot convert a Symbol value to a string
"" + sym; // TypeError: Cannot convert a Symbol value to a string
"".concat(sym); // TypeError: Cannot convert a Symbol value to a string
```

```js
const sym = Symbol("example");
String(sym); // "Symbol(example)"
```

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

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

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

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

See also
--------

* Text formatting guide


String.prototype.isWellFormed() - JavaScript

String.prototype.isWellFormed()
===============================

The **`isWellFormed()`** method of `String` values returns a boolean indicating whether this string contains any lone surrogates.

Syntax
------

```js
isWellFormed()
```

### Parameters

None.

### Return value

Returns `true` if this string does not contain any lone surrogates, `false` otherwise.

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

Strings in JavaScript are UTF-16 encoded. UTF-16 encoding has the concept of *surrogate pairs*, which is introduced in detail in the UTF-16 characters, Unicode code points, and grapheme clusters section.

`isWellFormed()` allows you to test whether a string is well-formed (i.e. does not contain any lone surrogates). Compared to a custom implementation, `isWellFormed()` is more efficient, as engines can directly access the internal representation of strings. If you need to convert a string to a well-formed string, use the `toWellFormed()` method. `isWellFormed()` allows you to handle ill-formed strings differently from well-formed strings, such as throwing an error or marking it as invalid.

Examples
--------

### Using isWellFormed()

```js
const strings = [
  // Lone leading surrogate
  "ab\uD800",
  "ab\uD800c",
  // Lone trailing surrogate
  "\uDFFFab",
  "c\uDFFFab",
  // Well-formed
  "abc",
  "ab\uD83D\uDE04c",
];

for (const str of strings) {
  console.log(str.isWellFormed());
}
// Logs:
// false
// false
// false
// false
// true
// true
```

### Avoiding errors in encodeURI()

`encodeURI` throws an error if the string passed is not well-formed. This can be avoided by using `isWellFormed()` to test the string before passing it to `encodeURI()`.

```js
const illFormed = "https://example.com/search?q=\uD800";

try {
  encodeURI(illFormed);
} catch (e) {
  console.log(e); // URIError: URI malformed
}

if (illFormed.isWellFormed()) {
  console.log(encodeURI(illFormed));
} else {
  console.warn("Ill-formed strings encountered."); // Ill-formed strings encountered.
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.iswellformed |

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

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

See also
--------

* Polyfill of `String.prototype.isWellFormed` in `core-js`
* `String.prototype.toWellFormed()`
* `String.prototype.normalize()`


String.prototype.sup() - JavaScript

String.prototype.sup()
======================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`sup()`** method of `String` values creates a string that embeds this string in a `<sup>` element (`<sup>str</sup>`), which causes this string to be displayed as superscript.

**Note:** All HTML wrapper methods are deprecated and only standardized for compatibility purposes. Use DOM APIs such as `document.createElement()` instead.

Syntax
------

```js
sup()
```

### Parameters

None.

### Return value

A string beginning with a `<sup>` start tag, then the text `str`, and then a `</sup>` end tag.

Examples
--------

### Using sup()

The code below creates an HTML string and then replaces the document's body with it:

```js
const contentString = "Hello, world";

document.body.innerHTML = contentString.sup();
```

This will create the following HTML:

```html
<sup>Hello, world</sup>
```

Instead of using `sup()` and creating HTML text directly, you should use DOM APIs such as `document.createElement()`. For example:

```js
const contentString = "Hello, world";
const elem = document.createElement("sup");
elem.innerText = contentString;
document.body.appendChild(elem);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.sup |

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

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

See also
--------

* Polyfill of `String.prototype.sup` in `core-js`
* HTML wrapper methods
* `<sup>`


String.prototype.big() - JavaScript

String.prototype.big()
======================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`big()`** method of `String` values creates a string that embeds this string in a `<big>` element (`<big>str</big>`), which causes this string to be displayed in a big font.

**Note:** All HTML wrapper methods are deprecated and only standardized for compatibility purposes. For the case of `big()`, the `<big>` element itself has been removed from the HTML specification and shouldn't be used anymore. Web developers should use CSS properties instead.

Syntax
------

```js
big()
```

### Parameters

None.

### Return value

A string beginning with a `<big>` start tag, then the text `str`, and then a `</big>` end tag.

Examples
--------

### Using big()

The code below creates an HTML string and then replaces the document's body with it:

```js
const contentString = "Hello, world";

document.body.innerHTML = contentString.big();
```

This will create the following HTML:

```html
<big>Hello, world</big>
```

**Warning:** This markup is invalid, because `big` is no longer a valid element.

Instead of using `big()` and creating HTML text directly, you should use CSS to manipulate fonts. For example, you can manipulate `font-size` through the `element.style` attribute:

```js
document.getElementById("yourElemId").style.fontSize = "2em";
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.big |

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

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

See also
--------

* Polyfill of `String.prototype.big` in `core-js`
* HTML wrapper methods
* `<big>`


String.prototype.indexOf() - JavaScript

String.prototype.indexOf()
==========================

The **`indexOf()`** method of `String` values searches this string and returns the index of the first occurrence of the specified substring. It takes an optional starting position and returns the first occurrence of the specified substring at an index greater than or equal to the specified number.

Try it
------

Syntax
------

```js
indexOf(searchString)
indexOf(searchString, position)
```

### Parameters

`searchString`

Substring to search for. All values are coerced to strings, so omitting it or passing `undefined` causes `indexOf()` to search for the string `"undefined"`, which is rarely what you want.

`position` Optional

The method returns the index of the first occurrence of the specified substring at a position greater than or equal to `position`, which defaults to `0`. If `position` is greater than the length of the calling string, the method doesn't search the calling string at all. If `position` is less than zero, the method behaves as it would if `position` were `0`.

* `'hello world hello'.indexOf('o', -5)` returns `4` — because it causes the method to behave as if the second argument were `0`, and the first occurrence of `o` at a position greater or equal to `0` is at position `4`.
* `'hello world hello'.indexOf('world', 12)` returns `-1` — because, while it's true the substring `world` occurs at index `6`, that position is not greater than or equal to `12`.
* `'hello world hello'.indexOf('o', 99)` returns `-1` — because `99` is greater than the length of `hello world hello`, which causes the method to not search the string at all.

### Return value

The index of the first occurrence of `searchString` found, or `-1` if not found.

#### Return value when using an empty search string

Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument:

```js
"hello world".indexOf(""); // returns 0
"hello world".indexOf("", 0); // returns 0
"hello world".indexOf("", 3); // returns 3
"hello world".indexOf("", 8); // returns 8
```

However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length:

```js
"hello world".indexOf("", 11); // returns 11
"hello world".indexOf("", 13); // returns 11
"hello world".indexOf("", 22); // returns 11
```

In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string.

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

Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1.

```js
"Blue Whale".indexOf("Blue"); // returns 0
"Blue Whale".indexOf("Blute"); // returns -1
"Blue Whale".indexOf("Whale", 0); // returns 5
"Blue Whale".indexOf("Whale", 5); // returns 5
"Blue Whale".indexOf("Whale", 7); // returns -1
"Blue Whale".indexOf(""); // returns 0
"Blue Whale".indexOf("", 9); // returns 9
"Blue Whale".indexOf("", 10); // returns 10
"Blue Whale".indexOf("", 11); // returns 10
```

 The `indexOf()` method is case sensitive. For example, the following
 expression returns `-1`:

```js
"Blue Whale".indexOf("blue"); // returns -1
```

### Checking occurrences

When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is `-1`:

```js
"Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale'
"Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale'
```

Examples
--------

### Using indexOf()

 The following example uses `indexOf()` to locate substrings in the string
 `"Brave new world"`.

```js
const str = "Brave new world";

console.log(str.indexOf("w")); // 8
console.log(str.indexOf("new")); // 6
```

### indexOf() and case-sensitivity

The following example defines two string variables.

 The variables contain the same string, except that the second string contains uppercase
 letters. The first `console.log()` method displays `19`. But
 because the `indexOf()` method is case sensitive, the string
 `"cheddar"` is not found in `myCapString`, so the second
 `console.log()` method displays `-1`.

```js
const myString = "brie, pepper jack, cheddar";
const myCapString = "Brie, Pepper Jack, Cheddar";

console.log(myString.indexOf("cheddar")); // 19
console.log(myCapString.indexOf("cheddar")); // -1
```

### Using indexOf() to count occurrences of a letter in a string

 The following example sets `count` to the number of occurrences of the
 letter `e` in the string `str`:

```js
const str = "To be, or not to be, that is the question.";
let count = 0;
let position = str.indexOf("e");

while (position !== -1) {
  count++;
  position = str.indexOf("e", position + 1);
}

console.log(count); // 4
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.indexof |

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

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

See also
--------

* `String.prototype.charAt()`
* `String.prototype.lastIndexOf()`
* `String.prototype.includes()`
* `String.prototype.split()`
* `Array.prototype.indexOf()`


String.prototype.repeat() - JavaScript

String.prototype.repeat()
=========================

 The **`repeat()`** method of `String` values constructs and returns a new string
 which contains the specified number of copies of this string, concatenated together.

Try it
------

Syntax
------

```js
repeat(count)
```

### Parameters

`count`

 An integer between `0` and
 `+Infinity`, indicating the
 number of times to repeat the string.

### Return value

A new string containing the specified number of copies of the given string.

### Exceptions

`RangeError`

Thrown if `count` is negative or if `count` overflows maximum string length.

Examples
--------

### Using repeat()

```js
"abc".repeat(-1); // RangeError
"abc".repeat(0); // ''
"abc".repeat(1); // 'abc'
"abc".repeat(2); // 'abcabc'
"abc".repeat(3.5); // 'abcabcabc' (count will be converted to integer)
"abc".repeat(1 / 0); // RangeError

({ toString: () => "abc", repeat: String.prototype.repeat }).repeat(2);
// 'abcabc' (repeat() is a generic method)
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.repeat |

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

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

See also
--------

* Polyfill of `String.prototype.repeat` in `core-js`
* `String.prototype.concat()`


String.prototype.toLocaleUpperCase() - JavaScript

String.prototype.toLocaleUpperCase()
====================================

The **`toLocaleUpperCase()`** method of `String` values returns this string converted to upper case, according to any locale-specific case mappings.

Try it
------

Syntax
------

```js
toLocaleUpperCase()
toLocaleUpperCase(locales)
```

### Parameters

`locales` Optional

A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see the parameter description on the `Intl` main page.

Unlike other methods that use the `locales` argument, `toLocaleUpperCase()` does not allow locale matching. Therefore, after checking the validity of the `locales` argument, `toLocaleUpperCase()` always uses the first locale in the list (or the default locale if the list is empty), even if this locale is not supported by the implementation.

### Return value

 A new string representing the calling string converted to upper case, according to any
 locale-specific case mappings.

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

 The `toLocaleUpperCase()` method returns the value of the string converted
 to upper case according to any locale-specific case mappings.
 `toLocaleUpperCase()` does not affect the value of the string itself. In most
 cases, this will produce the same result as `toUpperCase()`, but for some locales, such as Turkish, whose case mappings do not
 follow the default case mappings in Unicode, there may be a different result.

 Also notice that conversion is not necessarily a 1:1 character mapping, as some
 characters might result in two (or even more) characters when transformed to upper-case.
 Therefore the length of the result string can differ from the input length. This also
 implies that the conversion is not stable, so i.E. the following can return
 `false`:
 `x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()`

Examples
--------

### Using toLocaleUpperCase()

```js
"alphabet".toLocaleUpperCase(); // 'ALPHABET'

"Gesäß".toLocaleUpperCase(); // 'GESÄSS'

"i\u0307".toLocaleUpperCase("lt-LT"); // 'I'

const locales = ["lt", "LT", "lt-LT", "lt-u-co-phonebk", "lt-x-lietuva"];
"i\u0307".toLocaleUpperCase(locales); // 'I'
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.tolocaleuppercase |
| ECMAScript Internationalization API Specification # sup-string.prototype.tolocaleuppercase |

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

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

See also
--------

* `String.prototype.toLocaleLowerCase()`
* `String.prototype.toLowerCase()`
* `String.prototype.toUpperCase()`


String.prototype.match() - JavaScript

String.prototype.match()
========================

The **`match()`** method of `String` values retrieves the result of matching this string against a regular expression.

Try it
------

Syntax
------

```js
match(regexp)
```

### Parameters

`regexp`

A regular expression object, or any object that has a `Symbol.match` method.

If `regexp` is not a `RegExp` object and does not have a `Symbol.match` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`.

If you don't give any parameter and use the `match()` method directly, you will get an `Array` with an empty string: `[""]`, because this is equivalent to `match(/(?:)/)`.

### Return value

An `Array` whose contents depend on the presence or absence of the global (`g`) flag, or `null` if no matches are found.

* If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included.
* If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as `RegExp.prototype.exec()` (an array with some extra properties).
Description
-----------

The implementation of `String.prototype.match` itself is very simple — it simply calls the `Symbol.match` method of the argument with the string as the first parameter. The actual implementation comes from `RegExp.prototype[@@match]()`.

* If you need to know if a string matches a regular expression `RegExp`, use `RegExp.prototype.test()`.
* If you only want the first match found, you might want to use `RegExp.prototype.exec()` instead.
* If you want to obtain capture groups and the global flag is set, you need to use `RegExp.prototype.exec()` or `String.prototype.matchAll()` instead.

For more information about the semantics of `match()` when a regex is passed, see `RegExp.prototype[@@match]()`.

Examples
--------

### Using match()

In the following example, `match()` is used to find `"Chapter"` followed by one or more numeric characters followed by a decimal point and numeric character zero or more times.

The regular expression includes the `i` flag so that upper/lower case differences will be ignored.

```js
const str = "For more information, see Chapter 3.4.5.1";
const re = /see (chapter \d+(\.\d)\*)/i;
const found = str.match(re);

console.log(found);
// [
// 'see Chapter 3.4.5.1',
// 'Chapter 3.4.5.1',
// '.1',
// index: 22,
// input: 'For more information, see Chapter 3.4.5.1',
// groups: undefined
// ]
```

In the match result above, `'see Chapter 3.4.5.1'` is the whole match. `'Chapter 3.4.5.1'` was captured by `(chapter \d+(\.\d)*)`. `'.1'` was the last value captured by `(\.\d)`. The `index` property (`22`) is the zero-based index of the whole match. The `input` property is the original string that was parsed.

### Using global and ignoreCase flags with match()

The following example demonstrates the use of the global flag and ignore-case flag with `match()`. All letters `A` through `E` and `a` through `e` are returned, each its own element in the array.

```js
const str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const regexp = /[A-E]/gi;
const matches = str.match(regexp);

console.log(matches);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
```

**Note:** See also `String.prototype.matchAll()` and Advanced searching with flags.

### Using named capturing groups

In browsers which support named capturing groups, the following code captures `"fox"` or `"cat"` into a group named `animal`:

```js
const paragraph = "The quick brown fox jumps over the lazy dog. It barked.";

const capturingRegex = /(?<animal>fox|cat) jumps over/;
const found = paragraph.match(capturingRegex);
console.log(found.groups); // {animal: "fox"}
```

### Using match() with no parameter

```js
const str = "Nothing will come of nothing.";

str.match(); // returns [""]
```

### Using match() with a non-RegExp implementing @@match

If an object has a `Symbol.match` method, it can be used as a custom matcher. The return value of `Symbol.match` becomes the return value of `match()`.

```js
const str = "Hmm, this is interesting.";

str.match({
  [Symbol.match](str) {
    return ["Yes, it's interesting."];
  },
}); // returns ["Yes, it's interesting."]
```

### A non-RegExp as the parameter

When the `regexp` parameter is a string or a number, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`.

```js
const str1 =
  "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.";
const str2 =
  "My grandfather is 65 years old and My grandmother is 63 years old.";
const str3 = "The contract was declared null and void.";
str1.match("number"); // "number" is a string. returns ["number"]
str1.match(NaN); // the type of NaN is the number. returns ["NaN"]
str1.match(Infinity); // the type of Infinity is the number. returns ["Infinity"]
str1.match(+Infinity); // returns ["Infinity"]
str1.match(-Infinity); // returns ["-Infinity"]
str2.match(65); // returns ["65"]
str2.match(+65); // A number with a positive sign. returns ["65"]
str3.match(null); // returns ["null"]
```

This may have unexpected results if special characters are not properly escaped.

```js
console.log("123".match("1.3")); // [ "123" ]
```

This is a match because `.` in a regex matches any character. In order to make it only match specifically a dot character, you need to escape the input.

```js
console.log("123".match("1\\.3")); // null
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.match |

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

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

See also
--------

* Polyfill of `String.prototype.match` in `core-js` with fixes and implementation of modern behavior like `Symbol.match` support
* `String.prototype.matchAll()`
* `RegExp`
* `RegExp.prototype.exec()`
* `RegExp.prototype.test()`


FinalizationRegistry() constructor - JavaScript

FinalizationRegistry() constructor
==================================

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

Syntax
------

```js
new FinalizationRegistry(callbackFn)
```

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

### Parameters

`callback`

A function to be invoked each time a registered target value is garbage collected. Its return value is ignored. The function is called with the following arguments:

`heldValue`

The value that was passed to the second parameter of the `register()` method when the `target` object was registered.

Examples
--------

### Creating a new registry

You create the registry passing in the callback:

```js
const registry = new FinalizationRegistry((heldValue) => {
  // …
});
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-finalization-registry-constructor |

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

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

See also
--------

* `FinalizationRegistry`


FinalizationRegistry.prototype.unregister() - JavaScript

FinalizationRegistry.prototype.unregister()
===========================================

The **`unregister()`** method of `FinalizationRegistry` instances unregisters a target value from this `FinalizationRegistry`.

Syntax
------

```js
unregister(unregisterToken)
```

### Parameters

`unregisterToken`

The token used with the `register()` method when registering the target value. Multiple cells registered with the same `unregisterToken` will be unregistered together.

### Return value

A boolean value that is `true` if at least one cell was unregistered and `false` if no cell was unregistered.

### Exceptions

`TypeError`

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

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

 When a target value has been reclaimed, it is no longer registered in the registry.
 There is no need to call `unregister` in your cleanup callback. Only call
 `unregister` if you haven't received a cleanup callback and no longer need
 to receive one.

Examples
--------

### Using unregister

 This example shows registering a target object using that same object as the unregister
 token, then later unregistering it via `unregister`:

```js
class Thingy {
  static #cleanup = (label) => {
    // ^^^^^−−−−− held value
    console.error(
      `The "release" method was never called for the object with the label "${label}"`,
    );
  };
  #registry = new FinalizationRegistry(Thingy.#cleanup);

  /\*\*
 \* Constructs a `Thingy` instance.
 \* Be sure to call `release` when you're done with it.
 \*
 \* @param label A label for the `Thingy`.
 \*/
  constructor(label) {
    // vvvvv−−−−− held value
    this.#registry.register(this, label, this);
    // target −−−−−^^^^ ^^^^−−−−− unregister token
  }

  /\*\*
 \* Releases resources held by this `Thingy` instance.
 \*/
  release() {
    this.#registry.unregister(this);
    // ^^^^−−−−− unregister token
  }
}
```

 This example shows registering a target object using a different object as its
 unregister token:

```js
class Thingy {
  static #cleanup = (file) => {
    // ^^^^−−−−− held value
    console.error(
      `The "release" method was never called for the "Thingy" for the file "${file.name}"`,
    );
  };
  #registry = new FinalizationRegistry(Thingy.#cleanup);
  #file;

  /\*\*
 \* Constructs a `Thingy` instance for the given file.
 \* Be sure to call `release` when you're done with it.
 \*
 \* @param filename The name of the file.
 \*/
  constructor(filename) {
    this.#file = File.open(filename);
    // vvvvv−−−−− held value
    this.#registry.register(this, label, this.#file);
    // target −−−−−^^^^ ^^^^^^^^^^−−−−− unregister token
  }

  /\*\*
 \* Releases resources held by this `Thingy` instance.
 \*/
  release() {
    if (this.#file) {
      this.#registry.unregister(this.#file);
      // ^^^^^^^^^^−−−−− unregister token
      File.close(this.#file);
      this.#file = null;
    }
  }
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-finalization-registry.prototype.unregister |

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

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

See also
--------

* `FinalizationRegistry`


FinalizationRegistry.prototype.register() - JavaScript

FinalizationRegistry.prototype.register()
=========================================

The **`register()`** method of `FinalizationRegistry` instances registers an value with this `FinalizationRegistry` so that if the value is garbage-collected, the registry's callback may get called.

Syntax
------

```js
register(target, heldValue)
register(target, heldValue, unregisterToken)
```

### Parameters

`target`

The target value to register.

`heldValue`

The value to pass to the finalizer for this `target`. This cannot be the `target` itself but can be anything else, including functions and primitives.

`unregisterToken` Optional

A token that may be used with the `unregister` method later to unregister the target value. If provided (and not `undefined`), this must be an object or a non-registered symbol. If not provided, the target cannot be unregistered.

### Return value

None (`undefined`).

### Exceptions

`TypeError`

Thrown in one of the following cases:

* `target` is not an object or a non-registered symbol (object as opposed to primitives; functions are objects as well)
* `target` is the same as `heldvalue` (`target === heldValue`)
* `unregisterToken` is not an object or a non-registered symbol

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

 See the Avoid where possible
 and Notes on cleanup callbacks
 sections of the `FinalizationRegistry` page for important caveats.

Examples
--------

### Using register

 The following registers the value referenced by `target`,
 passing in the held value `"some value"` and passing the target itself
 as the unregistration token:

```js
registry.register(target, "some value", target);
```

 The following registers the value referenced by `target`,
 passing in another object as the held value, and not passing in any unregistration token
 (which means `target` can't be unregistered):

```js
registry.register(target, { useful: "info about target" });
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-finalization-registry.prototype.register |

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

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

See also
--------

* `FinalizationRegistry`


Date.prototype.setFullYear() - JavaScript

Date.prototype.setFullYear()
============================

The **`setFullYear()`** method of `Date` instances changes the year, month, and/or day of month for this date according to local time.

Try it
------

Syntax
------

```js
setFullYear(yearValue)
setFullYear(yearValue, monthValue)
setFullYear(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 same values as what are returned by `getMonth()` and `getDate()` are used.

If a parameter you specify is outside of the expected range, other parameters and the date information in the `Date` object are updated 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 setFullYear()

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

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

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

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

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

See also
--------

* `Date.prototype.getUTCFullYear()`
* `Date.prototype.setUTCFullYear()`
* `Date.prototype.setYear()`


Date.prototype.getUTCMonth() - JavaScript

Date.prototype.getUTCMonth()
============================

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

Try it
------

Syntax
------

```js
getUTCMonth()
```

### Parameters

None.

### Return value

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

Examples
--------

### Using getUTCMonth()

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

```js
const today = new Date();
const month = today.getUTCMonth();
```

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

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

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

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

See also
--------

* `Date.prototype.getMonth()`
* `Date.prototype.setUTCMonth()`


Date.prototype.getMilliseconds() - JavaScript

Date.prototype.getMilliseconds()
================================

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

Try it
------

Syntax
------

```js
getMilliseconds()
```

### Parameters

None.

### Return value

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

Examples
--------

### Using getMilliseconds()

The `milliseconds` variable has value `0`, based on the value of the `Date` object `xmas95`, which doesn't specify the milliseconds component, so it defaults to 0.

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

console.log(milliseconds); // 0
```

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

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

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.prototype.getUTCSeconds() - JavaScript

Date.prototype.getUTCSeconds()
==============================

The **`getUTCSeconds()`** method of `Date` instances returns the seconds in the specified date according to universal time.

Try it
------

Syntax
------

```js
getUTCSeconds()
```

### Parameters

None.

### Return value

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

Examples
--------

### Using getUTCSeconds()

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

```js
const today = new Date();
const seconds = today.getUTCSeconds();
```

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

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

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.toDateString() - JavaScript

Date.prototype.toDateString()
=============================

The **`toDateString()`** method of `Date` instances returns a string representing the date portion of this date interpreted in the local timezone.

Try it
------

Syntax
------

```js
toDateString()
```

### Parameters

None.

### Return value

A string representing the date portion of the given date (see description for the format). Returns `"Invalid Date"` if the date is invalid.

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

`Date` instances refer to a specific point in time. `toDateString()` interprets the date in the local timezone and formats the *date* part in English. It always uses the following format, separated by spaces:

1. First three letters of the week day name
2. First three letters of the month name
3. Two-digit day of the month, padded on the left a zero if necessary
4. Four-digit year (at least), padded on the left with zeros if necessary. May have a negative sign

For example: "Thu Jan 01 1970".

* If you only want to get the *time* part, use `toTimeString()`.
* If you want to get both the date and time, use `toString()`.
* If you want to make the date interpreted as UTC instead of local timezone, use `toUTCString()`.
* If you want to format the date in a more user-friendly format (e.g. localization), use `toLocaleDateString()`.
Examples
--------

### Using toDateString()

```js
const d = new Date(0);

console.log(d.toString()); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"
console.log(d.toDateString()); // "Thu Jan 01 1970"
```

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

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

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

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

See also
--------

* `Date.prototype.toLocaleDateString()`
* `Date.prototype.toTimeString()`
* `Date.prototype.toString()`


Date.prototype.getMinutes() - JavaScript

Date.prototype.getMinutes()
===========================

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

Try it
------

Syntax
------

```js
getMinutes()
```

### Parameters

None.

### Return value

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

Examples
--------

### Using getMinutes()

The `minutes` variable has value `15`, based on the value of the `Date` object `xmas95`.

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

console.log(minutes); // 15
```

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

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

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

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

See also
--------

* `Date.prototype.getUTCMinutes()`
* `Date.prototype.setMinutes()`


Date.prototype.setYear() - JavaScript

Date.prototype.setYear()
========================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`setYear()`** method of `Date` instances sets the year for a specified date according to local time.

However, the way the legacy `setYear()` method sets year values is different from how the preferred `setFullYear()` method sets year values — and in some cases, also different from how `new Date()` and `Date.parse()` set year values. Specifically, given two-digit numbers, such as `22` and `61`:

* `setYear()` interprets any two-digit number as an offset to `1900`; so `date.setYear(22)` results in the year value being set to `1922`, and `date.setYear(61)` results in the year value being set to `1961`. (In contrast, while `new Date(61, 1)` also results in the year value being set to `1961`, `new Date("2/1/22")` results in the year value being set to `2022`; and similarly for `Date.parse()`).
* `setFullYear()` does no special interpretation but instead uses the literal two-digit value as-is to set the year; so `date.setFullYear(61)` results in the year value being set to `0061`, and `date.setFullYear(22)` results in the year value being set to `0022`.

Because of those differences in behavior, you should no longer use the legacy `setYear()` method, but should instead use the preferred `setFullYear()` method.

Syntax
------

```js
setYear(yearValue)
```

### Parameters

`yearValue`

An integer.

### Return value

Changes the `Date` object in place, and returns its new timestamp. If `yearValue` 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 `yearValue` is a number between 0 and 99 (inclusive), then the year for
 `dateObj` is set to `1900 + yearValue`. Otherwise, the year for
 `dateObj` is set to `yearValue`.

Examples
--------

### Using setYear()

The first two lines set the year to 1996. The third sets the year to 2000.

```js
const theBigDay = new Date();

theBigDay.setYear(96);
theBigDay.setYear(1996);
theBigDay.setYear(2000);
```

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

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

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

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

See also
--------

* Polyfill of `Date.prototype.setYear` in `core-js`
* `Date.prototype.getFullYear()`
* `Date.prototype.getUTCFullYear()`
* `Date.prototype.setFullYear()`
* `Date.prototype.setUTCFullYear()`


Date.prototype.setMonth() - JavaScript

Date.prototype.setMonth()
=========================

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

Try it
------

Syntax
------

```js
setMonth(monthValue)
setMonth(monthValue, dateValue)
```

### Parameters

`monthValue`

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

`dateValue` Optional

An integer from 1 to 31 representing the day of the month.

### 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 `dateValue` parameter, the same value as what is returned by `getDate()` is used.

If a parameter you specify is outside of the expected range, other parameters and the date information in the `Date` object are updated accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1, and 3 is used for month.

 The current day of month will have an impact on the behavior of this method.
 Conceptually it will add the number of days given by the current day of the month to the
 1st day of the new month specified as the parameter, to return the new date.
 For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016.
 This is because in 2016 February had 29 days.

Examples
--------

### Using setMonth()

```js
const theBigDay = new Date();
theBigDay.setMonth(6);

//Watch out for end of month transitions
const endOfMonth = new Date(2016, 7, 31);
endOfMonth.setMonth(1);
console.log(endOfMonth); //Wed Mar 02 2016 00:00:00
```

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

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

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

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

See also
--------

* `Date.prototype.getMonth()`
* `Date.prototype.setUTCMonth()`


Date.prototype.getTime() - JavaScript

Date.prototype.getTime()
========================

The **`getTime()`** method of `Date` instances returns the number of milliseconds for this date since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.

Try it
------

Syntax
------

```js
getTime()
```

### Parameters

None.

### Return value

A number representing the timestamp, in milliseconds, of this date. Returns `NaN` if the date is invalid.

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

`Date` objects are fundamentally represented by a timestamp, and this method allows you to retrieve the timestamp. You can use this method to help assign a date and time to another `Date` object. This method is functionally equivalent to the `valueOf()` method.

### Reduced time precision

To offer protection against timing attacks and fingerprinting, the precision of `new Date().getTime()` 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
new Date().getTime();
// 1519211809934
// 1519211810362
// 1519211811670
// …

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

Examples
--------

### Using getTime() for copying dates

Constructing a date object with the identical time value.

```js
// Since month is zero based, birthday will be January 10, 1995
const birthday = new Date(1994, 12, 10);
const copy = new Date();
copy.setTime(birthday.getTime());
```

### Measuring execution time

Subtracting two subsequent `getTime()` calls on newly generated `Date` objects, give the time span between these two calls. This can be used to calculate the executing time of some operations. See also `Date.now()` to prevent instantiating unnecessary `Date` objects.

```js
let end, start;

start = new Date();
for (let i = 0; i < 1000; i++) {
  Math.sqrt(i);
}
end = new Date();

console.log(`Operation took ${end.getTime() - start.getTime()} msec`);
```

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

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

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

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

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

See also
--------

* `Date.prototype.setTime()`
* `Date.prototype.valueOf()`
* `Date.now()`


Date.prototype.setUTCMinutes() - JavaScript

Date.prototype.setUTCMinutes()
==============================

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

Try it
------

Syntax
------

```js
setUTCMinutes(minutesValue)
setUTCMinutes(minutesValue, secondsValue)
setUTCMinutes(minutesValue, secondsValue, msValue)
```

### Parameters

`minutesValue`

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 `secondsValue` and
 `msValue` parameters, the values returned from
 `getUTCSeconds()` and
 `getUTCMilliseconds()` methods are
 used.

 If a parameter you specify is outside of the expected range,
 `setUTCMinutes()` 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 setUTCMinutes()

```js
const theBigDay = new Date();
theBigDay.setUTCMinutes(43);
```

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

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

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

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

See also
--------

* `Date.prototype.getUTCMinutes()`
* `Date.prototype.setMinutes()`


Date.prototype.getUTCFullYear() - JavaScript

Date.prototype.getUTCFullYear()
===============================

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

Try it
------

Syntax
------

```js
getUTCFullYear()
```

### Parameters

None.

### Return value

An integer representing the year for the given date according to universal time. Returns `NaN` if the date is invalid.

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

Unlike `getYear()`, the value returned by `getUTCFullYear()` is an absolute number. For dates between the years 1000 and 9999, `getFullYear()` returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000.

Examples
--------

### Using getUTCFullYear()

The following example assigns the four-digit value of the current year to the variable `year`.

```js
const today = new Date();
const year = today.getUTCFullYear();
```

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

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

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

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

See also
--------

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


Date.prototype.toJSON() - JavaScript

Date.prototype.toJSON()
=======================

The **`toJSON()`** method of `Date` instances returns a string representing this date in the same ISO format as `toISOString()`.

Try it
------

Syntax
------

```js
toJSON()
```

### Parameters

None.

### Return value

A string representing the given date in the date time string format according to universal time, or `null` when the date is invalid. For valid dates, the return value is the same as that of `toISOString()`.

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

The `toJSON()` method is automatically called by `JSON.stringify()` when a `Date` object is stringified. This method is generally intended to, by default, usefully serialize `Date` objects during JSON serialization, which can then be deserialized using the `Date()` constructor as the reviver of `JSON.parse()`.

The method first attempts to convert its `this` value to a primitive by calling its `[@@toPrimitive]()` (with `"number"` as hint), `valueOf()`, and `toString()` methods, in that order. If the result is a non-finite number, `null` is returned. (This generally corresponds to an invalid date, whose `valueOf()` returns `NaN`.) Otherwise, if the converted primitive is not a number or is a finite number, the return value of `this.toISOString()` is returned.

Note that the method does not check whether the `this` value is a valid `Date` object. However, calling `Date.prototype.toJSON()` on non-`Date` objects fails unless the object's number primitive representation is `NaN`, or the object also has a `toISOString()` method.

Examples
--------

### Using toJSON()

```js
const jsonDate = new Date(0).toJSON(); // '1970-01-01T00:00:00.000Z'
const backToDate = new Date(jsonDate);

console.log(jsonDate); // 1970-01-01T00:00:00.000Z
```

### Serialization round-tripping

When parsing JSON containing date strings, you can use the `Date()` constructor to revive them into the original date objects.

```js
const fileData = {
  author: "Maria",
  title: "Date.prototype.toJSON()",
  createdAt: new Date(2019, 3, 15),
  updatedAt: new Date(2020, 6, 26),
};
const response = JSON.stringify(fileData);

// Imagine transmission through network

const data = JSON.parse(response, (key, value) => {
  if (key === "createdAt" || key === "updatedAt") {
    return new Date(value);
  }
  return value;
});

console.log(data);
```

**Note:** The reviver of `JSON.parse()` must be specific to the payload shape you expect, because the serialization is *lossy*: it's not possible to distinguish between a string that represents a Date and a normal string.

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

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

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

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

See also
--------

* `Date.prototype.toLocaleDateString()`
* `Date.prototype.toTimeString()`
* `Date.prototype.toUTCString()`


Date.prototype.setMilliseconds() - JavaScript

Date.prototype.setMilliseconds()
================================

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

Try it
------

Syntax
------

```js
setMilliseconds(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 you specify a number outside the expected range, the date information in the `Date` object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds.

Examples
--------

### Using setMilliseconds()

```js
const theBigDay = new Date();
theBigDay.setMilliseconds(100);
```

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

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

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


Date() constructor - JavaScript

Date() constructor
==================

The **`Date()`** constructor creates `Date` objects. When called as a function, it returns a string representing the current time.

Try it
------

Syntax
------

```js
new Date()
new Date(value)
new Date(dateString)
new Date(dateObject)

new Date(year, monthIndex)
new Date(year, monthIndex, day)
new Date(year, monthIndex, day, hours)
new Date(year, monthIndex, day, hours, minutes)
new Date(year, monthIndex, day, hours, minutes, seconds)
new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)

Date()
```

**Note:** `Date()` can be called with or without `new`, but with different effects. See Return value.

### Parameters

There are five basic forms for the `Date()` constructor:

#### No parameters

When no parameters are provided, the newly-created `Date` object represents the current date and time as of the time of instantiation. The returned date's timestamp is the same as the number returned by `Date.now()`.

#### Time value or timestamp number

`value`

An integer value representing the timestamp (the number of milliseconds since midnight at the beginning of January 1, 1970, UTC — a.k.a. the epoch).

#### Date string

`dateString`

A string value representing a date, parsed and interpreted using the same algorithm implemented by `Date.parse()`. See date time string format for caveats on using different formats.

#### Date object

`dateObject`

An existing `Date` object. This effectively makes a copy of the existing `Date` object with the same date and time. This is equivalent to `new Date(dateObject.valueOf())`, except the `valueOf()` method is not called.

When one parameter is passed to the `Date()` constructor, `Date` instances are specially treated. All other values are converted to primitives. If the result is a string, it will be parsed as a date string. Otherwise, the resulting primitive is further coerced to a number and treated as a timestamp.

#### Individual date and time component values

Given at least a year and month, this form of `Date()` returns a `Date` object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (`1` for `day` and `0` for every other component). The parameter values are all evaluated against the local time zone, rather than UTC. `Date.UTC()` accepts similar parameters but interprets the components as UTC and returns a timestamp.

If any parameter overflows its defined bounds, it "carries over". For example, if a `monthIndex` greater than `11` is passed in, those months will cause the year to increment; if a `minutes` greater than `59` is passed in, `hours` will increment accordingly, etc. Therefore, `new Date(1990, 12, 1)` will return January 1st, 1991; `new Date(2020, 5, 19, 25, 65)` will return 2:05 A.M. June 20th, 2020.

Similarly, if any parameter underflows, it "borrows" from the higher positions. For example, `new Date(2020, 5, 0)` will return May 31st, 2020.

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

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

`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

Calling `new Date()` (the `Date()` constructor) returns a `Date` object. If called with an invalid date string, or if the date to be constructed will have a timestamp less than `-8,640,000,000,000,000` or greater than `8,640,000,000,000,000` milliseconds, it returns an invalid date (a `Date` object whose `toString()` method returns `"Invalid Date"` and `valueOf()` method returns `NaN`).

Calling the `Date()` function (without the `new` keyword) returns a string representation of the current date and time, exactly as `new Date().toString()` does. Any arguments given in a `Date()` function call (without the `new` keyword) are ignored; regardless of whether it's called with an invalid date string — or even called with any arbitrary object or other primitive as an argument — it always returns a string representation of the current date and time.

Examples
--------

### Several ways to create a Date object

The following examples show several ways to create JavaScript dates:

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

### Passing a non-Date, non-string, non-number value

If the `Date()` constructor is called with one parameter which is not a `Date` instance, it will be coerced to a primitive and then checked whether it's a string. For example, `new Date(undefined)` is different from `new Date()`:

```js
console.log(new Date(undefined)); // Invalid Date
```

This is because `undefined` is already a primitive but not a string, so it will be coerced to a number, which is `NaN` and therefore not a valid timestamp. On the other hand, `null` will be coerced to `0`.

```js
console.log(new Date(null)); // 1970-01-01T00:00:00.000Z
```

Arrays would be coerced to a string via `Array.prototype.toString()`, which joins the elements with commas. However, the resulting string for any array with more than one element is not a valid ISO 8601 date string, so its parsing behavior would be implementation-defined. **Do not pass arrays to the `Date()` constructor.**

```js
console.log(new Date(["2020-06-19", "17:13"]));
// 2020-06-19T17:13:00.000Z in Chrome, since it recognizes "2020-06-19,17:13"
// "Invalid Date" in Firefox
```

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

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

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

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

See also
--------

* `Date`


Date.prototype.setUTCDate() - JavaScript

Date.prototype.setUTCDate()
===========================

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

Try it
------

Syntax
------

```js
setUTCDate(dateValue)
```

### Parameters

`dateValue`

An integer from 1 to 31 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 the `dateValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly.

For example, if 0 is provided for `dateValue`, the date will be set to the last day of the previous month. If you use 40 for `dateValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July.

If a negative number is provided for `dateValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month.

Examples
--------

### Using setUTCDate()

```js
const theBigDay = new Date();
theBigDay.setUTCDate(20);
```

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

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

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

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

See also
--------

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


Date.prototype.setTime() - JavaScript

Date.prototype.setTime()
========================

The **`setTime()`** method of `Date` instances changes the timestamp for this date, which is the number of milliseconds since the epoch, defined as the midnight at the beginning of January 1, 1970, UTC.

Try it
------

Syntax
------

```js
setTime(timeValue)
```

### Parameters

`timeValue`

An integer representing the new timestamp — the number of milliseconds since the midnight at the beginning of January 1, 1970, UTC.

### Return value

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

Examples
--------

### Using setTime()

```js
const theBigDay = new Date("1999-07-01");
const sameAsBigDay = new Date();
sameAsBigDay.setTime(theBigDay.getTime());
```

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

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

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

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

See also
--------

* `Date.prototype.getTime()`
* `Date.prototype.setUTCHours()`


Date.prototype.setMinutes() - JavaScript

Date.prototype.setMinutes()
===========================

The **`setMinutes()`** method of `Date` instances changes the minutes for this date according to local time.

Try it
------

Syntax
------

```js
setMinutes(minutesValue)
setMinutes(minutesValue, secondsValue)
setMinutes(minutesValue, secondsValue, msValue)
```

### Parameters

`minutesValue`

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 `secondsValue` and `msValue` parameters, the same values as what are returned by `getSeconds()` and `getMilliseconds()` are used.

If a parameter you specify is outside of the expected range, other parameters and the date information in the `Date` object are updated accordingly. For example, if you specify 100 for `secondsValue`, the minutes is incremented by 1 (`minutesValue + 1`), and 40 is used for seconds.

Examples
--------

### Using setMinutes()

```js
const theBigDay = new Date();
theBigDay.setMinutes(45);
```

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

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

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.prototype.getUTCHours() - JavaScript

Date.prototype.getUTCHours()
============================

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

Try it
------

Syntax
------

```js
getUTCHours()
```

### Parameters

None.

### Return value

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

Examples
--------

### Using getUTCHours()

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

```js
const today = new Date();
const hours = today.getUTCHours();
```

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

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

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

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

See also
--------

* `Date.prototype.getHours()`
* `Date.prototype.setUTCHours()`


Date.prototype.getDay() - JavaScript

Date.prototype.getDay()
=======================

The **`getDay()`** method of `Date` instances returns the day of the week for this date according to local time, where 0 represents Sunday. For the day of the month, see `Date.prototype.getDate()`.

Try it
------

Syntax
------

```js
getDay()
```

### Parameters

None.

### Return value

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

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

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

```js
const valentines = new Date("1995-02-14");
const day = valentines.getDay();
const dayNames = ["Sunday", "Monday", "Tuesday" /\* , … \*/];

console.log(dayNames[day]); // "Monday"
```

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

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

Examples
--------

### Using getDay()

The `weekday` variable has value `1`, based on the value of the `Date` object `xmas95`, because December 25, 1995 is a Monday.

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

console.log(weekday); // 1
```

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

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

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.getYear() - JavaScript

Date.prototype.getYear()
========================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`getYear()`** method of `Date` instances returns the year for this date according to local time. Because `getYear()` does not return full years ("year 2000 problem"), it is deprecated and has been replaced by the `getFullYear()` method.

Syntax
------

```js
getYear()
```

### Parameters

None.

### Return value

An integer representing the year for the given date according to local time, minus 1900. Returns `NaN` if the date is invalid.

* For years greater than or equal to 2000, the value is 100 or greater. For example, if the year is 2026, `getYear()` returns 126.
* For years between and including 1900 and 1999, the value returned by `getYear()` is between 0 and 99. For example, if the year is 1976, `getYear()` returns 76.
* For years less than 1900, the value returned by `getYear()` is less than 0. For example, if the year is 1800, `getYear()` returns -100.

This method essentially returns the value of `getFullYear()` minus 1900. You should use `getFullYear()` instead, so that the year is specified in full.

Examples
--------

### Years between 1900 and 1999

The second statement assigns the value 95 to the variable `year`.

```js
const xmas = new Date("1995-12-25");
const year = xmas.getYear(); // returns 95
```

### Years above 1999

The second statement assigns the value 100 to the variable `year`.

```js
const xmas = new Date("2000-12-25");
const year = xmas.getYear(); // returns 100
```

### Years below 1900

The second statement assigns the value -100 to the variable `year`.

```js
const xmas = new Date("1800-12-25");
const year = xmas.getYear(); // returns -100
```

### Setting and getting a year between 1900 and 1999

The third statement assigns the value 95 to the variable `year`, representing the year 1995.

```js
const xmas = new Date("2015-12-25");
xmas.setYear(95);
const year = xmas.getYear(); // returns 95
```

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

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

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

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

See also
--------

* Polyfill of `Date.prototype.getYear` in `core-js`
* `Date.prototype.getFullYear()`
* `Date.prototype.getUTCFullYear()`
* `Date.prototype.setYear()`


Date.prototype.toTimeString() - JavaScript

Date.prototype.toTimeString()
=============================

The **`toTimeString()`** method of `Date` instances returns a string representing the time portion of this date interpreted in the local timezone.

Try it
------

Syntax
------

```js
toTimeString()
```

### Parameters

None.

### Return value

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

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

`Date` instances refer to a specific point in time. `toTimeString()` interprets the date in the local timezone and formats the *time* part in English. It always uses the format of `hh:mm:ss GMT±xxxx (TZ)`, where:

| Format String | Description |
| --- | --- |
| `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 |
| `±xxxx` | The local timezone's offset — two digits for hours and two digits for minutes (e.g. `-0500`, `+0800`) |
| `TZ` | The timezone's name (e.g. `PDT`, `PST`) |

For example: "04:42:04 GMT+0000 (Coordinated Universal Time)".

* If you only want to get the *date* part, use `toDateString()`.
* If you want to get both the date and time, use `toString()`.
* If you want to make the date interpreted as UTC instead of local timezone, use `toUTCString()`.
* If you want to format the date in a more user-friendly format (e.g. localization), use `toLocaleTimeString()`.
Examples
--------

### Using toTimeString()

```js
const d = new Date(0);

console.log(d.toString()); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"
console.log(d.toTimeString()); // "00:00:00 GMT+0000 (Coordinated Universal Time)"
```

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

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

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

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

See also
--------

* `Date.prototype.toLocaleTimeString()`
* `Date.prototype.toDateString()`
* `Date.prototype.toString()`


Date.prototype.getUTCDate() - JavaScript

Date.prototype.getUTCDate()
===========================

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

Try it
------

Syntax
------

```js
getUTCDate()
```

### Parameters

None.

### Return value

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

Examples
--------

### Using getUTCDate()

The following example assigns the day of month of the current date to the variable `dayOfMonth`.

```js
const today = new Date();
const dayOfMonth = today.getUTCDate();
```

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

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

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.toString() - JavaScript

Date.prototype.toString()
=========================

The **`toString()`** method of `Date` instances returns a string representing this date interpreted in the local timezone.

Try it
------

Syntax
------

```js
toString()
```

### Parameters

None.

### Return value

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

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

The `toString()` method is part of the type coercion protocol. Because `Date` has a `[@@toPrimitive]()` method, that method always takes priority over `toString()` when a `Date` object is implicitly coerced to a string. However, `Date.prototype[@@toPrimitive]()` still calls `this.toString()` internally.

The `Date` object overrides the `toString()` method of `Object`. `Date.prototype.toString()` returns a string representation of the Date as interpreted in the local timezone, containing both the date and the time — it joins the string representation specified in `toDateString()` and `toTimeString()` together, adding a space in between. For example: "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)".

`Date.prototype.toString()` must be called on `Date` instances. If the `this` value does not inherit from `Date.prototype`, a `TypeError` is thrown.

* If you only want to get the *date* part, use `toDateString()`.
* If you only want to get the *time* part, use `toTimeString()`.
* If you want to make the date interpreted as UTC instead of local timezone, use `toUTCString()`.
* If you want to format the date in a more user-friendly format (e.g. localization), use `toLocaleString()`.
Examples
--------

### Using toString()

```js
const d = new Date(0);
console.log(d.toString()); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"
```

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

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

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

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

See also
--------

* `Object.prototype.toString()`
* `Date.prototype.toDateString()`
* `Date.prototype.toLocaleString()`
* `Date.prototype.toTimeString()`


Date.prototype.setHours() - JavaScript

Date.prototype.setHours()
=========================

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

Try it
------

Syntax
------

```js
setHours(hoursValue)
setHours(hoursValue, minutesValue)
setHours(hoursValue, minutesValue, secondsValue)
setHours(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 same values as what are returned by `getMinutes()`, `getSeconds()`, and `getMilliseconds()` are used.

If a parameter you specify is outside of the expected range, other parameters and the date information in the `Date` object are updated accordingly. For example, if you specify 100 for `secondsValue`, the minutes are incremented by 1 (`minutesValue + 1`), and 40 is used for seconds.

Examples
--------

### Using setHours()

```js
const theBigDay = new Date();
theBigDay.setHours(7);
```

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

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

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

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

See also
--------

* `Date.prototype.getHours()`
* `Date.prototype.setUTCHours()`


Date.prototype.getFullYear() - JavaScript

Date.prototype.getFullYear()
============================

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

Use this method instead of the `getYear()` method.

Try it
------

Syntax
------

```js
getFullYear()
```

### Parameters

None.

### Return value

An integer representing the year for the given date according to local time. Returns `NaN` if the date is invalid.

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

Unlike `getYear()`, the value returned by `getFullYear()` is an absolute number. For dates between the years 1000 and 9999, `getFullYear()` returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000.

Examples
--------

### Using getFullYear()

The `fullYear` variable has value `1995`, based on the value of the `Date` object `xmas95`.

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

console.log(fullYear); // 1995
```

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

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

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.getYear()`


Date.prototype.setUTCMonth() - JavaScript

Date.prototype.setUTCMonth()
============================

The **`setUTCMonth()`** method of `Date` instances changes the month and/or day of the month for this date according to universal time.

Try it
------

Syntax
------

```js
setUTCMonth(monthValue)
setUTCMonth(monthValue, dateValue)
```

### Parameters

`monthValue`

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

`dateValue` Optional

An integer from 1 to 31 representing the day of the month.

### 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 `dateValue` parameter, the value returned from the
 `getUTCDate()` method is used.

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

Examples
--------

### Using setUTCMonth()

```js
const theBigDay = new Date();
theBigDay.setUTCMonth(11);
```

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

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

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[@@toPrimitive]() - JavaScript

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

The **`[@@toPrimitive]()`** method of `Date` instances returns a primitive value representing this date. It may either be a string or a number, depending on the hint given.

Try it
------

Syntax
------

```js
date[Symbol.toPrimitive](hint)
```

### Parameters

`hint`

A string representing the type of the primitive value to return. The following values are valid:

* `"string"` or `"default"`: The method should return a string.
* `"number"`: The method should return a number.

### Return value

If `hint` is `"string"` or `"default"`, this method returns a string by coercing the `this` value to a string (first trying `toString()` then trying `valueOf()`).

If `hint` is `"number"`, this method returns a number by coercing the `this` value to a number (first trying `valueOf()` then trying `toString()`).

### Exceptions

`TypeError`

Thrown if the `hint` argument is not one of the three valid values.

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

The `[@@toPrimitive]()` method is part of the type coercion protocol. JavaScript always calls the `[@@toPrimitive]()` method in priority to convert an object to a primitive value. You rarely need to invoke the `[@@toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.

The `[@@toPrimitive]()` method of the `Date` object returns a primitive value by either invoking `this.valueOf()` and returning a number, or invoking `this.toString()` and returning a string. It exists to override the default primitive coercion process to return a string instead of a number, because primitive coercion, by default, calls `valueOf()` before `toString()`. With the custom `[@@toPrimitive]()`, `new Date(0) + 1` returns `"Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)1"` (a string) instead of `1` (a number).

Examples
--------

### Using [@@toPrimitive]()

```js
const d = new Date(0); // 1970-01-01T00:00:00.000Z

d[Symbol.toPrimitive]("string"); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"
d[Symbol.toPrimitive]("number"); // 0
d[Symbol.toPrimitive]("default"); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-date.prototype-@@toprimitive |

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

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

See also
--------

* `Symbol.toPrimitive`


Date.prototype.valueOf() - JavaScript

Date.prototype.valueOf()
========================

The **`valueOf()`** method of `Date` instances returns the number of milliseconds for this date since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.

Try it
------

Syntax
------

```js
valueOf()
```

### Parameters

None.

### Return value

A number representing the timestamp, in milliseconds, of this date. Returns `NaN` if the date is invalid.

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

The `valueOf()` method is part of the type coercion protocol. Because `Date` has a `[@@toPrimitive]()` method, that method always takes priority over `valueOf()` when a `Date` object is implicitly coerced to a number. However, `Date.prototype[@@toPrimitive]()` still calls `this.valueOf()` internally.

The `Date` object overrides the `valueOf()` method of `Object`. `Date.prototype.valueOf()` returns the timestamp of the date, which is functionally equivalent to the `Date.prototype.getTime()` method.

Examples
--------

### Using valueOf()

```js
const d = new Date(0); // 1970-01-01T00:00:00.000Z
console.log(d.valueOf()); // 0
```

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

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

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

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

See also
--------

* `Object.prototype.valueOf()`
* `Date.prototype.getTime()`


Date.prototype.setUTCSeconds() - JavaScript

Date.prototype.setUTCSeconds()
==============================

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

Try it
------

Syntax
------

```js
setUTCSeconds(secondsValue)
setUTCSeconds(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
 `getUTCMilliseconds()` method is
 used.

 If a parameter you specify is outside of the expected range,
 `setUTCSeconds()` 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 setUTCSeconds()

```js
const theBigDay = new Date();
theBigDay.setUTCSeconds(20);
```

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

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

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.toLocaleDateString() - JavaScript

Date.prototype.toLocaleDateString()
===================================

The **`toLocaleDateString()`** method of `Date` instances returns a string with a language-sensitive representation of the date portion 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
toLocaleDateString()
toLocaleDateString(locales)
toLocaleDateString(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. The `timeStyle` option must be undefined, or a `TypeError` would be thrown. If `weekday`, `year`, `month`, and `day` are all undefined, then `year`, `month`, and `day` 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 date 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 `toLocaleDateString()` 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 `toLocaleDateString()` to static values.

Examples
--------

### Using toLocaleDateString()

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));

// toLocaleDateString() without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(date.toLocaleDateString());
// "12/11/2012" 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, `toLocaleDateString()` 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 toLocaleDateStringSupportsLocales() {
  return (
    typeof Intl === "object" &&
    !!Intl &&
    typeof Intl.DateTimeFormat === "function"
  );
}
```

### Using locales

This example shows some of the variations in localized date 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
console.log(date.toLocaleDateString("en-US"));
// "12/20/2012"

// British English uses day-month-year order
console.log(date.toLocaleDateString("en-GB"));
// "20/12/2012"

// Korean uses year-month-day order
console.log(date.toLocaleDateString("ko-KR"));
// "2012. 12. 20."

// Event for Persian, It's hard to manually convert date to Solar Hijri
console.log(date.toLocaleDateString("fa-IR"));
// "۱۳۹۱/۹/۳۰"

// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(date.toLocaleDateString("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.toLocaleDateString("ja-JP-u-ca-japanese"));
// "24/12/20"

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

### Using options

The results provided by `toLocaleDateString()` 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.toLocaleDateString("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.toLocaleDateString("en-US", options));
// "Thursday, December 20, 2012, UTC"
```

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

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

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

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

See also
--------

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


Date.prototype.toISOString() - JavaScript

Date.prototype.toISOString()
============================

The **`toISOString()`** method of `Date` instances returns a string representing this date in the date time string format, a *simplified* format based on ISO 8601, which is always 24 or 27 characters long (`YYYY-MM-DDTHH:mm:ss.sssZ` or `±YYYYYY-MM-DDTHH:mm:ss.sssZ`, respectively). The timezone is always UTC, as denoted by the suffix `Z`.

Try it
------

Syntax
------

```js
toISOString()
```

### Parameters

None.

### Return value

A string representing the given date in the date time string format according to universal time. It's the same format as the one required to be recognized by `Date.parse()`.

### Exceptions

`RangeError`

Thrown if the date is invalid or if it corresponds to a year that cannot be represented in the date string format.

Examples
--------

### Using toISOString()

```js
const d = new Date(0);

console.log(d.toISOString()); // "1970-01-01T00:00:00.000Z"
```

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

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

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

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

See also
--------

* `Date.prototype.toLocaleDateString()`
* `Date.prototype.toString()`
* `Date.prototype.toUTCString()`