repo_id
stringlengths 22
103
| file_path
stringlengths 41
147
| content
stringlengths 181
193k
| __index_level_0__
int64 0
0
|
---|---|---|---|
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/now/index.md | ---
title: Date.now()
slug: Web/JavaScript/Reference/Global_Objects/Date/now
page-type: javascript-static-method
browser-compat: javascript.builtins.Date.now
---
{{JSRef}}
The **`Date.now()`** static method returns the number of milliseconds elapsed since the [epoch](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date), which is defined as the midnight at the beginning of January 1, 1970, UTC.
{{EmbedInteractiveExample("pages/js/date-now.html")}}
## Syntax
```js-nolint
Date.now()
```
### Parameters
None.
### Return value
A number representing the [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date), in milliseconds, of the current time.
## Description
### Reduced time precision
To offer protection against timing attacks and [fingerprinting](/en-US/docs/Glossary/Fingerprinting), the precision of `Date.now()` might get rounded depending on browser settings. In Firefox, the `privacy.reduceTimerPrecision` preference is enabled by default and defaults to 2ms. You can also enable `privacy.resistFingerprinting`, in which case the precision will be 100ms or the value of `privacy.resistFingerprinting.reduceTimerPrecision.microseconds`, whichever is larger.
```js
// reduced time precision (2ms) in Firefox 60
Date.now();
// 1519211809934
// 1519211810362
// 1519211811670
// …
// reduced time precision with `privacy.resistFingerprinting` enabled
Date.now();
// 1519129853500
// 1519129858900
// 1519129864400
// …
```
## Examples
### Measuring time elapsed
You can use `Date.now()` to get the current time in milliseconds, then subtract a previous time to find out how much time elapsed between the two calls.
```js
const start = Date.now();
doSomeLongRunningProcess();
console.log(`Time elapsed: ${Date.now() - start} ms`);
```
For more complex scenarios, you may want to use the [performance API](/en-US/docs/Web/API/Performance_API/High_precision_timing) instead.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Date.now` in `core-js`](https://github.com/zloirock/core-js#ecmascript-date)
- {{domxref("Performance.now()")}}
- {{domxref("console/time_static", "console.time()")}}
- {{domxref("console/timeEnd_static", "console.timeEnd()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/getutchours/index.md | ---
title: Date.prototype.getUTCHours()
slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCHours
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getUTCHours
---
{{JSRef}}
The **`getUTCHours()`** method of {{jsxref("Date")}} instances returns the hours for this date according to universal time.
{{EmbedInteractiveExample("pages/js/date-getutchours.html")}}
## Syntax
```js-nolint
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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## 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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getHours()")}}
- {{jsxref("Date.prototype.setUTCHours()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/setutcminutes/index.md | ---
title: Date.prototype.setUTCMinutes()
slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.setUTCMinutes
---
{{JSRef}}
The **`setUTCMinutes()`** method of {{jsxref("Date")}} instances changes the minutes for this date according to universal time.
{{EmbedInteractiveExample("pages/js/date-setutcminutes.html")}}
## Syntax
```js-nolint
setUTCMinutes(minutesValue)
setUTCMinutes(minutesValue, secondsValue)
setUTCMinutes(minutesValue, secondsValue, msValue)
```
### Parameters
- `minutesValue`
- : An integer between 0 and 59 representing the minutes.
- `secondsValue` {{optional_inline}}
- : An integer between 0 and 59 representing the seconds. If you specify `secondsValue`, you must also specify `minutesValue`.
- `msValue` {{optional_inline}}
- : An integer between 0 and 999 representing the milliseconds. If you specify `msValue`, you must also specify `minutesValue` and `secondsValue`.
### Return value
Changes the {{jsxref("Date")}} object in place, and returns its new [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). If a parameter is `NaN` (or other values that get [coerced](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to `NaN`, such as `undefined`), the date is set to [Invalid Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) and `NaN` is returned.
## Description
If you do not specify the `secondsValue` and
`msValue` parameters, the values returned from
{{jsxref("Date/getUTCSeconds", "getUTCSeconds()")}} and
{{jsxref("Date/getUTCMilliseconds", "getUTCMilliseconds()")}} methods are
used.
If a parameter you specify is outside of the expected range,
`setUTCMinutes()` attempts to update the date information in the
{{jsxref("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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCMinutes()")}}
- {{jsxref("Date.prototype.setMinutes()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/setminutes/index.md | ---
title: Date.prototype.setMinutes()
slug: Web/JavaScript/Reference/Global_Objects/Date/setMinutes
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.setMinutes
---
{{JSRef}}
The **`setMinutes()`** method of {{jsxref("Date")}} instances changes the minutes for this date according to local time.
{{EmbedInteractiveExample("pages/js/date-setminutes.html")}}
## Syntax
```js-nolint
setMinutes(minutesValue)
setMinutes(minutesValue, secondsValue)
setMinutes(minutesValue, secondsValue, msValue)
```
### Parameters
- `minutesValue`
- : An integer between 0 and 59 representing the minutes.
- `secondsValue` {{optional_inline}}
- : An integer between 0 and 59 representing the seconds. If you specify `secondsValue`, you must also specify `minutesValue`.
- `msValue` {{optional_inline}}
- : An integer between 0 and 999 representing the milliseconds. If you specify `msValue`, you must also specify `minutesValue` and `secondsValue`.
### Return value
Changes the {{jsxref("Date")}} object in place, and returns its new [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). If a parameter is `NaN` (or other values that get [coerced](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to `NaN`, such as `undefined`), the date is set to [Invalid Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_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 {{jsxref("Date/getSeconds", "getSeconds()")}} and {{jsxref("Date/getMilliseconds", "getMilliseconds()")}} are used.
If a parameter you specify is outside of the expected range, other parameters and the date information in the {{jsxref("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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getMinutes()")}}
- {{jsxref("Date.prototype.setUTCMinutes()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/totimestring/index.md | ---
title: Date.prototype.toTimeString()
slug: Web/JavaScript/Reference/Global_Objects/Date/toTimeString
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.toTimeString
---
{{JSRef}}
The **`toTimeString()`** method of {{jsxref("Date")}} instances returns a string representing the time portion of this date interpreted in the local timezone.
{{EmbedInteractiveExample("pages/js/date-totimestring.html", "shorter")}}
## Syntax
```js-nolint
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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Description
{{jsxref("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 {{jsxref("Date/toDateString", "toDateString()")}}.
- If you want to get both the date and time, use {{jsxref("Date/toString", "toString()")}}.
- If you want to make the date interpreted as UTC instead of local timezone, use {{jsxref("Date/toUTCString", "toUTCString()")}}.
- If you want to format the date in a more user-friendly format (e.g. localization), use {{jsxref("Date/toLocaleTimeString", "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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.toLocaleTimeString()")}}
- {{jsxref("Date.prototype.toDateString()")}}
- {{jsxref("Date.prototype.toString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/setutcfullyear/index.md | ---
title: Date.prototype.setUTCFullYear()
slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.setUTCFullYear
---
{{JSRef}}
The **`setUTCFullYear()`** method of {{jsxref("Date")}} instances changes the year for this date according to universal time.
{{EmbedInteractiveExample("pages/js/date-setutcfullyear.html")}}
## Syntax
```js-nolint
setUTCFullYear(yearValue)
setUTCFullYear(yearValue, monthValue)
setUTCFullYear(yearValue, monthValue, dateValue)
```
### Parameters
- `yearValue`
- : An integer representing the year. For example, 1995.
- `monthValue` {{optional_inline}}
- : An integer representing the month: 0 for January, 1 for February, and so on.
- `dateValue` {{optional_inline}}
- : 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 {{jsxref("Date")}} object in place, and returns its new [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). If a parameter is `NaN` (or other values that get [coerced](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to `NaN`, such as `undefined`), the date is set to [Invalid Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) and `NaN` is returned.
## Description
If you do not specify the `monthValue` and
`dateValue` parameters, the values returned from the
{{jsxref("Date/getUTCMonth", "getUTCMonth()")}} and
{{jsxref("Date/getUTCDate", "getUTCDate()")}} methods are used.
If a parameter you specify is outside of the expected range,
`setUTCFullYear()` attempts to update the other parameters and the date
information in the {{jsxref("Date")}} object accordingly. For example, if you specify 15
for `monthValue`, the year is incremented by 1
(`yearValue + 1`), and 3 is used for the month.
## Examples
### Using setUTCFullYear()
```js
const theBigDay = new Date();
theBigDay.setUTCFullYear(1997);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCFullYear()")}}
- {{jsxref("Date.prototype.setFullYear()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/setdate/index.md | ---
title: Date.prototype.setDate()
slug: Web/JavaScript/Reference/Global_Objects/Date/setDate
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.setDate
---
{{JSRef}}
The **`setDate()`** method of {{jsxref("Date")}} instances changes the day of the month for this date according to local time.
{{EmbedInteractiveExample("pages/js/date-setdate.html")}}
## Syntax
```js-nolint
setDate(dateValue)
```
### Parameters
- `dateValue`
- : An integer representing the day of the month.
### Return value
Changes the {{jsxref("Date")}} object in place, and returns its new [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). If `dateValue` is `NaN` (or other values that get [coerced](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to `NaN`, such as `undefined`), the date is set to [Invalid Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) and `NaN` is returned.
## Description
If you specify a number outside the expected range, the date information in the {{jsxref("Date")}} object is updated accordingly. For example, if the `Date` object holds June 1st, a `dateValue` of 40 changes the date to July 10th, while a `dateValue` of 0 changes the date to the last day of the previous month, May 31st.
## Examples
### Using setDate()
```js
const theBigDay = new Date(1962, 6, 7, 12); // noon of 1962-07-07 (7th of July 1962, month is 0-indexed)
const theBigDay2 = new Date(theBigDay).setDate(24); // 1962-07-24 (24th of July 1962)
const theBigDay3 = new Date(theBigDay).setDate(32); // 1962-08-01 (1st of August 1962)
const theBigDay4 = new Date(theBigDay).setDate(22); // 1962-07-22 (22nd of July 1962)
const theBigDay5 = new Date(theBigDay).setDate(0); // 1962-06-30 (30th of June 1962)
const theBigDay6 = new Date(theBigDay).setDate(98); // 1962-10-06 (6th of October 1962)
const theBigDay7 = new Date(theBigDay).setDate(-50); // 1962-05-11 (11th of May 1962)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date/Date", "Date()")}}
- {{jsxref("Date.prototype.getDate()")}}
- {{jsxref("Date.prototype.setUTCDate()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/getminutes/index.md | ---
title: Date.prototype.getMinutes()
slug: Web/JavaScript/Reference/Global_Objects/Date/getMinutes
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getMinutes
---
{{JSRef}}
The **`getMinutes()`** method of {{jsxref("Date")}} instances returns the minutes for this date according to local time.
{{EmbedInteractiveExample("pages/js/date-getminutes.html", "shorter")}}
## Syntax
```js-nolint
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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Examples
### Using getMinutes()
The `minutes` variable has value `15`, based on the value of the {{jsxref("Date")}} object `xmas95`.
```js
const xmas95 = new Date("1995-12-25T23:15:30");
const minutes = xmas95.getMinutes();
console.log(minutes); // 15
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCMinutes()")}}
- {{jsxref("Date.prototype.setMinutes()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/setutcmonth/index.md | ---
title: Date.prototype.setUTCMonth()
slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.setUTCMonth
---
{{JSRef}}
The **`setUTCMonth()`** method of {{jsxref("Date")}} instances changes the month and/or day of the month for this date according to universal time.
{{EmbedInteractiveExample("pages/js/date-setutcmonth.html")}}
## Syntax
```js-nolint
setUTCMonth(monthValue)
setUTCMonth(monthValue, dateValue)
```
### Parameters
- `monthValue`
- : An integer representing the month: 0 for January, 1 for February, and so on.
- `dateValue` {{optional_inline}}
- : An integer from 1 to 31 representing the day of the month.
### Return value
Changes the {{jsxref("Date")}} object in place, and returns its new [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). If a parameter is `NaN` (or other values that get [coerced](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to `NaN`, such as `undefined`), the date is set to [Invalid Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) and `NaN` is returned.
## Description
If you do not specify the `dateValue` parameter, the value returned from the
{{jsxref("Date/getUTCDate", "getUTCDate()")}} method is used.
If a parameter you specify is outside of the expected range, `setUTCMonth()`
attempts to update the date information in the {{jsxref("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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCMonth()")}}
- {{jsxref("Date.prototype.setMonth()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/setutcmilliseconds/index.md | ---
title: Date.prototype.setUTCMilliseconds()
slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCMilliseconds
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.setUTCMilliseconds
---
{{JSRef}}
The **`setUTCMilliseconds()`** method of {{jsxref("Date")}} instances changes the milliseconds for this date according to universal time.
{{EmbedInteractiveExample("pages/js/date-setutcmilliseconds.html")}}
## Syntax
```js-nolint
setUTCMilliseconds(millisecondsValue)
```
### Parameters
- `millisecondsValue`
- : An integer between 0 and 999 representing the milliseconds.
### Return value
Changes the {{jsxref("Date")}} object in place, and returns its new [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). If `millisecondsValue` is `NaN` (or other values that get [coerced](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to `NaN`, such as `undefined`), the date is set to [Invalid Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) and `NaN` is returned.
## Description
If a parameter you specify is outside of the expected range,
`setUTCMilliseconds()` attempts to update the date information in the
{{jsxref("Date")}} object accordingly. For example, if you use 1100 for
`millisecondsValue`, the seconds stored in the {{jsxref("Date")}}
object will be incremented by 1, and 100 will be used for milliseconds.
## Examples
### Using setUTCMilliseconds()
```js
const theBigDay = new Date();
theBigDay.setUTCMilliseconds(500);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCMilliseconds()")}}
- {{jsxref("Date.prototype.setMilliseconds()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/getmilliseconds/index.md | ---
title: Date.prototype.getMilliseconds()
slug: Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getMilliseconds
---
{{JSRef}}
The **`getMilliseconds()`** method of {{jsxref("Date")}} instances returns the milliseconds for this date according to local time.
{{EmbedInteractiveExample("pages/js/date-getmilliseconds.html", "shorter")}}
## Syntax
```js-nolint
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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Examples
### Using getMilliseconds()
The `milliseconds` variable has value `0`, based on the value of the {{jsxref("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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCMilliseconds()")}}
- {{jsxref("Date.prototype.setMilliseconds()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/getmonth/index.md | ---
title: Date.prototype.getMonth()
slug: Web/JavaScript/Reference/Global_Objects/Date/getMonth
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getMonth
---
{{JSRef}}
The **`getMonth()`** method of {{jsxref("Date")}} instances returns the month for this date according to local time, as a zero-based value (where zero indicates the first month of the year).
{{EmbedInteractiveExample("pages/js/date-getmonth.html", "shorter")}}
## Syntax
```js-nolint
getMonth()
```
### Parameters
None.
### Return value
An integer, between 0 and 11, representing the month for the given date according to local time: 0 for January, 1 for February, and so on. Returns `NaN` if the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Description
The return value of `getMonth()` is zero-based, which is useful for indexing into arrays of months, for example:
```js
const valentines = new Date("1995-02-14");
const month = valentines.getMonth();
const monthNames = ["January", "February", "March" /* , … */];
console.log(monthNames[month]); // "February"
```
However, for the purpose of internationalization, you should prefer using {{jsxref("Intl.DateTimeFormat")}} with the `options` parameter instead.
```js
const options = { month: "long" };
console.log(new Intl.DateTimeFormat("en-US", options).format(valentines));
// "February"
console.log(new Intl.DateTimeFormat("de-DE", options).format(valentines));
// "Februar"
```
## Examples
### Using getMonth()
The `month` variable has value `11`, based on the value of the {{jsxref("Date")}} object `xmas95`.
```js
const xmas95 = new Date("1995-12-25T23:15:30");
const month = xmas95.getMonth();
console.log(month); // 11
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCMonth()")}}
- {{jsxref("Date.prototype.setMonth()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/settime/index.md | ---
title: Date.prototype.setTime()
slug: Web/JavaScript/Reference/Global_Objects/Date/setTime
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.setTime
---
{{JSRef}}
The **`setTime()`** method of {{jsxref("Date")}} instances changes the [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) for this date, which is the number of milliseconds since the [epoch](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date), defined as the midnight at the beginning of January 1, 1970, UTC.
{{EmbedInteractiveExample("pages/js/date-settime.html", "taller")}}
## Syntax
```js-nolint
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 {{jsxref("Date")}} object in place, and returns its new [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). If `timeValue` is `NaN` (or other values that get [coerced](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to `NaN`, such as `undefined`), the date is set to [Invalid Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getTime()")}}
- {{jsxref("Date.prototype.setUTCHours()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/getday/index.md | ---
title: Date.prototype.getDay()
slug: Web/JavaScript/Reference/Global_Objects/Date/getDay
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getDay
---
{{JSRef}}
The **`getDay()`** method of {{jsxref("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 {{jsxref("Date.prototype.getDate()")}}.
{{EmbedInteractiveExample("pages/js/date-getday.html", "shorter")}}
## Syntax
```js-nolint
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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## 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 {{jsxref("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 {{jsxref("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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCDate()")}}
- {{jsxref("Date.prototype.getUTCDay()")}}
- {{jsxref("Date.prototype.setDate()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/getutcseconds/index.md | ---
title: Date.prototype.getUTCSeconds()
slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCSeconds
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getUTCSeconds
---
{{JSRef}}
The **`getUTCSeconds()`** method of {{jsxref("Date")}} instances returns the seconds in the specified date according to universal time.
{{EmbedInteractiveExample("pages/js/date-getutcseconds.html", "shorter")}}
## Syntax
```js-nolint
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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## 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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getSeconds()")}}
- {{jsxref("Date.prototype.setUTCSeconds()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/tolocaledatestring/index.md | ---
title: Date.prototype.toLocaleDateString()
slug: Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.toLocaleDateString
---
{{JSRef}}
The **`toLocaleDateString()`** method of {{jsxref("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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) 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 {{jsxref("Intl.DateTimeFormat")}} object and use its {{jsxref("Intl/DateTimeFormat/format", "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.
{{EmbedInteractiveExample("pages/js/date-tolocaledatestring.html", "taller")}}
## Syntax
```js-nolint
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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/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_inline}}
- : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#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_inline}}
- : An object adjusting the output format. Corresponds to the [`options`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. The `timeStyle` option must be undefined, or a {{jsxref("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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) 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 {{jsxref("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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DateTimeFormat")}}
- {{jsxref("Date.prototype.toLocaleString()")}}
- {{jsxref("Date.prototype.toLocaleTimeString()")}}
- {{jsxref("Date.prototype.toString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/getutcfullyear/index.md | ---
title: Date.prototype.getUTCFullYear()
slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCFullYear
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getUTCFullYear
---
{{JSRef}}
The **`getUTCFullYear()`** method of {{jsxref("Date")}} instances returns the year for this date according to universal time.
{{EmbedInteractiveExample("pages/js/date-getutcfullyear.html")}}
## Syntax
```js-nolint
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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Description
Unlike {{jsxref("Date/getYear", "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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getFullYear()")}}
- {{jsxref("Date.prototype.setFullYear()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/gettimezoneoffset/index.md | ---
title: Date.prototype.getTimezoneOffset()
slug: Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getTimezoneOffset
---
{{JSRef}}
The **`getTimezoneOffset()`** method of {{jsxref("Date")}} instances returns the difference, in minutes, between this date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone.
{{EmbedInteractiveExample("pages/js/date-gettimezoneoffset.html")}}
## Syntax
```js-nolint
getTimezoneOffset()
```
### Parameters
None.
### Return value
A number representing the difference, in minutes, between the date as evaluated in the UTC time zone and as evaluated in the local time zone. The actual local time algorithm is implementation-defined, and the return value is allowed to be zero in runtimes without appropriate data. Returns `NaN` if the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Description
`date.getTimezoneOffset()` returns the difference, in minutes, between `date` as evaluated in the UTC time zone and as evaluated in the local time zone — that is, the time zone of the host system in which the browser is being used (if the code is run from the Web in a browser), or otherwise the host system of whatever JavaScript runtime (for example, a Node.js environment) the code is executed in.
### Negative values and positive values
The number of minutes returned by `getTimezoneOffset()` is positive if the local time zone is behind UTC, and negative if the local time zone is ahead of UTC. For example, for UTC+10, `-600` will be returned.
| Current time zone | Return value |
| ----------------- | ------------ |
| UTC-8 | 480 |
| UTC | 0 |
| UTC+3 | -180 |
### Varied results in Daylight Saving Time (DST) regions
In a region that annually shifts in and out of Daylight Saving Time (DST), as `date` varies, the number of minutes returned by calling `getTimezoneOffset()` can be non-uniform.
> **Note:** `getTimezoneOffset()`'s behavior will never differ based on the time when the code is run — its behavior is always consistent when running in the same region. Only the value of `date` affects the result.
> **Note:** [Many countries have experimented with not changing the time twice a year](https://en.wikipedia.org/wiki/Daylight_saving_time_by_country#Past_observance) and this has meant that DST has continued over the winter too. For example in the UK DST lasted from 2:00AM 18 February 1968 to 3:00AM 31 October 1971, so during the winter the clocks were not set back.
In most implementations, the [IANA time zone database](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database) (tzdata) is used to precisely determine the offset of the local timezone at the moment of the `date`. However, if such information is unavailable, an implementation may return zero.
## Examples
### Using getTimezoneOffset()
```js
// Create a Date instance for the current time
const currentLocalDate = new Date();
// Create a Date instance for 03:24 GMT-0200 on May 1st in 2016
const laborDay2016at0324GMTminus2 = new Date("2016-05-01T03:24:00-02:00");
currentLocalDate.getTimezoneOffset() ===
laborDay2016at0324GMTminus2.getTimezoneOffset();
// true, always, in any timezone that doesn't annually shift in and out of DST
// false, sometimes, in any timezone that annually shifts in and out of DST
```
### getTimezoneOffset() and DST
In regions that use DST, the return value may change based on the time of the year `date` is in. Below is the output in a runtime in New York, where the timezone is UTC-05:00.
```js
const nyOffsetSummer = new Date("2022-02-01").getTimezoneOffset(); // 300
const nyOffsetWinter = new Date("2022-08-01").getTimezoneOffset(); // 240
```
### getTimezoneOffset() and historical data
Due to historical reasons, the timezone a region is in can be constantly changing, even disregarding DST. For example, below is the output in a runtime in Shanghai, where the timezone is UTC+08:00.
```js
const shModernOffset = new Date("2022-01-27").getTimezoneOffset(); // -480
const shHistoricalOffset = new Date("1943-01-27").getTimezoneOffset(); // -540
```
This is because during the [Sino-Japanese War](https://en.wikipedia.org/wiki/Second_Sino-Japanese_War) when Shanghai was under Japanese control, the timezone was changed to UTC+09:00 to align with Japan's (in effect, it was a "year-round DST"), and this was recorded in the IANA database.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/setseconds/index.md | ---
title: Date.prototype.setSeconds()
slug: Web/JavaScript/Reference/Global_Objects/Date/setSeconds
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.setSeconds
---
{{JSRef}}
The **`setSeconds()`** method of {{jsxref("Date")}} instances changes the seconds and/or milliseconds for this date according to local time.
{{EmbedInteractiveExample("pages/js/date-setseconds.html")}}
## Syntax
```js-nolint
setSeconds(secondsValue)
setSeconds(secondsValue, msValue)
```
### Parameters
- `secondsValue`
- : An integer between 0 and 59 representing the seconds.
- `msValue` {{optional_inline}}
- : An integer between 0 and 999 representing the milliseconds.
### Return value
Changes the {{jsxref("Date")}} object in place, and returns its new [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). If a parameter is `NaN` (or other values that get [coerced](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to `NaN`, such as `undefined`), the date is set to [Invalid Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) and `NaN` is returned.
## Description
If you do not specify the `msValue` parameter, the value returned
from the {{jsxref("Date/getMilliseconds", "getMilliseconds()")}} method is
used.
If a parameter you specify is outside of the expected range, `setSeconds()`
attempts to update the date information in the {{jsxref("Date")}} object accordingly.
For example, if you use 100 for `secondsValue`, the minutes stored
in the {{jsxref("Date")}} object will be incremented by 1, and 40 will be used for
seconds.
## Examples
### Using setSeconds()
```js
const theBigDay = new Date();
theBigDay.setSeconds(30);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getSeconds()")}}
- {{jsxref("Date.prototype.setUTCSeconds()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/setfullyear/index.md | ---
title: Date.prototype.setFullYear()
slug: Web/JavaScript/Reference/Global_Objects/Date/setFullYear
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.setFullYear
---
{{JSRef}}
The **`setFullYear()`** method of {{jsxref("Date")}} instances changes the year, month, and/or day of month for this date according to local time.
{{EmbedInteractiveExample("pages/js/date-setfullyear.html")}}
## Syntax
```js-nolint
setFullYear(yearValue)
setFullYear(yearValue, monthValue)
setFullYear(yearValue, monthValue, dateValue)
```
### Parameters
- `yearValue`
- : An integer representing the year. For example, 1995.
- `monthValue` {{optional_inline}}
- : An integer representing the month: 0 for January, 1 for February, and so on.
- `dateValue` {{optional_inline}}
- : 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 {{jsxref("Date")}} object in place, and returns its new [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). If a parameter is `NaN` (or other values that get [coerced](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to `NaN`, such as `undefined`), the date is set to [Invalid Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_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 {{jsxref("Date/getMonth", "getMonth()")}} and {{jsxref("Date/getDate", "getDate()")}} are used.
If a parameter you specify is outside of the expected range, other parameters and the date information in the {{jsxref("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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCFullYear()")}}
- {{jsxref("Date.prototype.setUTCFullYear()")}}
- {{jsxref("Date.prototype.setYear()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/getutcminutes/index.md | ---
title: Date.prototype.getUTCMinutes()
slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCMinutes
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getUTCMinutes
---
{{JSRef}}
The **`getUTCMinutes()`** method of {{jsxref("Date")}} instances returns the minutes for this date according to universal time.
{{EmbedInteractiveExample("pages/js/date-getutcminutes.html")}}
## Syntax
```js-nolint
getUTCMinutes()
```
### Parameters
None.
### Return value
An integer, between 0 and 59, representing the minutes for the given date according to universal time. Returns `NaN` if the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Examples
### Using getUTCMinutes()
The following example assigns the minutes portion of the current time to the variable `minutes`.
```js
const today = new Date();
const minutes = today.getUTCMinutes();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getMinutes()")}}
- {{jsxref("Date.prototype.setUTCMinutes()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/utc/index.md | ---
title: Date.UTC()
slug: Web/JavaScript/Reference/Global_Objects/Date/UTC
page-type: javascript-static-method
browser-compat: javascript.builtins.Date.UTC
---
{{JSRef}}
The **`Date.UTC()`** static method accepts parameters representing the date and time components similar to the {{jsxref("Date")}} constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.
{{EmbedInteractiveExample("pages/js/date-utc.html")}}
## Syntax
```js-nolint
Date.UTC(year)
Date.UTC(year, monthIndex)
Date.UTC(year, monthIndex, day)
Date.UTC(year, monthIndex, day, hour)
Date.UTC(year, monthIndex, day, hour, minute)
Date.UTC(year, monthIndex, day, hour, minute, second)
Date.UTC(year, monthIndex, day, hour, minute, second, millisecond)
```
### Parameters
- `year`
- : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years).
- `monthIndex` {{optional_inline}}
- : Integer value representing the month, beginning with `0` for January to `11` for December. Defaults to `0`.
- `day` {{optional_inline}}
- : Integer value representing the day of the month. Defaults to `1`.
- `hours` {{optional_inline}}
- : Integer value between `0` and `23` representing the hour of the day. Defaults to `0`.
- `minutes` {{optional_inline}}
- : Integer value representing the minute segment of a time. Defaults to `0`.
- `seconds` {{optional_inline}}
- : Integer value representing the second segment of a time. Defaults to `0`.
- `milliseconds` {{optional_inline}}
- : Integer value representing the millisecond segment of a time. Defaults to `0`.
### Return value
A number representing the [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) of the given date. Returns `NaN` if the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Description
Years between `0` and `99` are converted to a year in the 20th century `(1900 + year)`. For example, `95` is converted to the year `1995`.
The `UTC()` method differs from the {{jsxref("Date/Date", "Date()")}} constructor in three ways:
1. `Date.UTC()` uses universal time instead of the local time.
2. `Date.UTC()` returns a time value as a number instead of creating a {{jsxref("Date")}} object.
3. When passed a single number, `Date.UTC()` interprets it as a year instead of a timestamp.
If a parameter is outside of the expected range, the `UTC()` method updates the other parameters to accommodate the value. For example, if `15` is used for `monthIndex`, the year will be incremented by 1 `(year + 1)` and `3` will be used for the month.
Because `UTC()` is a static method of `Date`, you always use it as `Date.UTC()`, rather than as a method of a `Date` object you created.
## Examples
### Using Date.UTC()
The following statement creates a {{jsxref("Date")}} object with the arguments treated as UTC instead of local:
```js
const utcDate = new Date(Date.UTC(2018, 11, 1, 0, 0, 0));
```
### Behavior of Date.UTC() with one argument
`Date.UTC()` when passed one argument used to have inconsistent behavior, because implementations only kept the behavior consistent with the {{jsxref("Date/Date", "Date()")}} constructor, which does not interpret a single argument as the year number. Implementations are now required to treat omitted `monthIndex` as `0`, instead of coercing it to `NaN`.
```js
Date.UTC(2017); // 1483228800000
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.parse()")}}
- {{jsxref("Date")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/getfullyear/index.md | ---
title: Date.prototype.getFullYear()
slug: Web/JavaScript/Reference/Global_Objects/Date/getFullYear
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getFullYear
---
{{JSRef}}
The **`getFullYear()`** method of {{jsxref("Date")}} instances returns the year for this date according to local time.
Use this method instead of the {{jsxref("Date/getYear", "getYear()")}} method.
{{EmbedInteractiveExample("pages/js/date-getfullyear.html", "shorter")}}
## Syntax
```js-nolint
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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Description
Unlike {{jsxref("Date/getYear", "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 {{jsxref("Date")}} object `xmas95`.
```js
const xmas95 = new Date("1995-12-25T23:15:30");
const fullYear = xmas95.getFullYear();
console.log(fullYear); // 1995
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCFullYear()")}}
- {{jsxref("Date.prototype.setFullYear()")}}
- {{jsxref("Date.prototype.getYear()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/setutchours/index.md | ---
title: Date.prototype.setUTCHours()
slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCHours
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.setUTCHours
---
{{JSRef}}
The **`setUTCHours()`** method of {{jsxref("Date")}} instances changes the hours, minutes, seconds, and/or milliseconds for this date according to universal time.
{{EmbedInteractiveExample("pages/js/date-setutchours.html")}}
## Syntax
```js-nolint
setUTCHours(hoursValue)
setUTCHours(hoursValue, minutesValue)
setUTCHours(hoursValue, minutesValue, secondsValue)
setUTCHours(hoursValue, minutesValue, secondsValue, msValue)
```
### Parameters
- `hoursValue`
- : An integer between 0 and 23 representing the hours.
- `minutesValue` {{optional_inline}}
- : An integer between 0 and 59 representing the minutes.
- `secondsValue` {{optional_inline}}
- : An integer between 0 and 59 representing the seconds. If you specify `secondsValue`, you must also specify `minutesValue`.
- `msValue` {{optional_inline}}
- : An integer between 0 and 999 representing the milliseconds. If you specify `msValue`, you must also specify `minutesValue` and `secondsValue`.
### Return value
Changes the {{jsxref("Date")}} object in place, and returns its new [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). If a parameter is `NaN` (or other values that get [coerced](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to `NaN`, such as `undefined`), the date is set to [Invalid Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) and `NaN` is returned.
## Description
If you do not specify the `minutesValue`,
`secondsValue`, and `msValue` parameters,
the values returned from the {{jsxref("Date/getUTCMinutes", "getUTCMinutes()")}}, {{jsxref("Date/getUTCSeconds", "getUTCSeconds()")}},
and {{jsxref("Date/getUTCMilliseconds", "getUTCMilliseconds()")}} methods
are used.
If a parameter you specify is outside of the expected range, `setUTCHours()`
attempts to update the date information in the {{jsxref("Date")}} object accordingly.
For example, if you use 100 for `secondsValue`, the minutes will
be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds.
## Examples
### Using setUTCHours()
```js
const theBigDay = new Date();
theBigDay.setUTCHours(8);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCHours()")}}
- {{jsxref("Date.prototype.setHours()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/gettime/index.md | ---
title: Date.prototype.getTime()
slug: Web/JavaScript/Reference/Global_Objects/Date/getTime
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getTime
---
{{JSRef}}
The **`getTime()`** method of {{jsxref("Date")}} instances returns the number of milliseconds for this date since the [epoch](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date), which is defined as the midnight at the beginning of January 1, 1970, UTC.
{{EmbedInteractiveExample("pages/js/date-gettime.html", "shorter")}}
## Syntax
```js-nolint
getTime()
```
### Parameters
None.
### Return value
A number representing the [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date), in milliseconds, of this date. Returns `NaN` if the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Description
`Date` objects are fundamentally represented by a [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date), and this method allows you to retrieve the timestamp. You can use this method to help assign a date and time to another {{jsxref("Date")}} object. This method is functionally equivalent to the {{jsxref("Date/valueof", "valueOf()")}} method.
### Reduced time precision
To offer protection against timing attacks and [fingerprinting](/en-US/docs/Glossary/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 {{jsxref("Date")}} objects, give the time span between these two calls. This can be used to calculate the executing time of some operations. See also {{jsxref("Date.now()")}} to prevent instantiating unnecessary {{jsxref("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 {{domxref("performance_property", "Web Performance API", "", 1)}}'s high-resolution time feature, {{domxref("Performance.now()")}} can provide more reliable and precise measurements of elapsed time than {{jsxref("Date.now()")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.setTime()")}}
- {{jsxref("Date.prototype.valueOf()")}}
- {{jsxref("Date.now()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/toutcstring/index.md | ---
title: Date.prototype.toUTCString()
slug: Web/JavaScript/Reference/Global_Objects/Date/toUTCString
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.toUTCString
---
{{JSRef}}
The **`toUTCString()`** method of {{jsxref("Date")}} instances returns a string representing this date in the [RFC 7231](https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.1.1) format, with negative years allowed. The timezone is always UTC. `toGMTString()` is an alias of this method.
{{EmbedInteractiveExample("pages/js/date-toutcstring.html", "shorter")}}
## Syntax
```js-nolint
toUTCString()
```
### Parameters
None.
### Return value
A string representing the given date using the UTC time zone (see description for the format). Returns `"Invalid Date"` if the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Description
The value returned by `toUTCString()` is a string in the form `Www, dd Mmm yyyy hh:mm:ss GMT`, where:
| Format String | Description |
| ------------- | ------------------------------------------------------------ |
| `Www` | Day of week, as three letters (e.g. `Sun`, `Mon`) |
| `dd` | Day of month, as two digits with leading zero if required |
| `Mmm` | Month, as three letters (e.g. `Jan`, `Feb`) |
| `yyyy` | Year, as four or more digits with leading zeroes if required |
| `hh` | Hour, as two digits with leading zero if required |
| `mm` | Minute, as two digits with leading zero if required |
| `ss` | Seconds, as two digits with leading zero if required |
### Aliasing
JavaScript's `Date` API was inspired by Java's `java.util.Date` library (while the latter had become de facto legacy since Java 1.1 in 1997). In particular, the Java `Date` class had a method called `toGMTString` — which was poorly named, because the [Greenwich Mean Time](https://en.wikipedia.org/wiki/Greenwich_Mean_Time) is not equivalent to the [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time), while JavaScript dates always operate by UTC time. For web compatibility reasons, `toGMTString` remains as an alias to `toUTCString`, and they refer to the exact same function object. This means:
```js
Date.prototype.toGMTString.name === "toUTCString";
```
## Examples
### Using toUTCString()
```js
const d = new Date(0);
console.log(d.toUTCString()); // 'Thu, 01 Jan 1970 00:00:00 GMT'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.toLocaleString()")}}
- {{jsxref("Date.prototype.toString()")}}
- {{jsxref("Date.prototype.toISOString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/valueof/index.md | ---
title: Date.prototype.valueOf()
slug: Web/JavaScript/Reference/Global_Objects/Date/valueOf
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.valueOf
---
{{JSRef}}
The **`valueOf()`** method of {{jsxref("Date")}} instances returns the number of milliseconds for this date since the [epoch](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date), which is defined as the midnight at the beginning of January 1, 1970, UTC.
{{EmbedInteractiveExample("pages/js/date-valueof.html")}}
## Syntax
```js-nolint
valueOf()
```
### Parameters
None.
### Return value
A number representing the [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date), in milliseconds, of this date. Returns `NaN` if the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Description
The `valueOf()` method is part of the [type coercion protocol](/en-US/docs/Web/JavaScript/Data_structures#type_coercion). Because `Date` has a [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/@@toPrimitive) method, that method always takes priority over `valueOf()` when a `Date` object is implicitly [coerced to a number](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). However, `Date.prototype[@@toPrimitive]()` still calls `this.valueOf()` internally.
The {{jsxref("Date")}} object overrides the {{jsxref("Object/valueOf", "valueOf()")}} method of {{jsxref("Object")}}. `Date.prototype.valueOf()` returns the timestamp of the date, which is functionally equivalent to the {{jsxref("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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Object.prototype.valueOf()")}}
- {{jsxref("Date.prototype.getTime()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/date/index.md | ---
title: Date() constructor
slug: Web/JavaScript/Reference/Global_Objects/Date/Date
page-type: javascript-constructor
browser-compat: javascript.builtins.Date.Date
---
{{JSRef}}
The **`Date()`** constructor creates {{jsxref("Date")}} objects. When called as a function, it returns a string representing the current time.
{{EmbedInteractiveExample("pages/js/date-constructor.html")}}
## Syntax
```js-nolint
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`](/en-US/docs/Web/JavaScript/Reference/Operators/new), but with different effects. See [Return value](#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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) is the same as the number returned by {{jsxref("Date.now()")}}.
#### Time value or timestamp number
- `value`
- : An integer value representing the [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) (the number of milliseconds since midnight at the beginning of January 1, 1970, UTC — a.k.a. the [epoch](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date)).
#### Date string
- `dateString`
- : A string value representing a date, parsed and interpreted using the same algorithm implemented by {{jsxref("Date.parse()")}}. See [date time string format](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#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](/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion). 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. {{jsxref("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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years).
- `monthIndex`
- : Integer value representing the month, beginning with `0` for January to `11` for December.
- `day` {{optional_inline}}
- : Integer value representing the day of the month. Defaults to `1`.
- `hours` {{optional_inline}}
- : Integer value between `0` and `23` representing the hour of the day. Defaults to `0`.
- `minutes` {{optional_inline}}
- : Integer value representing the minute segment of a time. Defaults to `0`.
- `seconds` {{optional_inline}}
- : Integer value representing the second segment of a time. Defaults to `0`.
- `milliseconds` {{optional_inline}}
- : Integer value representing the millisecond segment of a time. Defaults to `0`.
### Return value
Calling `new Date()` (the `Date()` constructor) returns a [`Date`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) (a `Date` object whose {{jsxref("Date/toString", "toString()")}} method returns `"Invalid Date"` and {{jsxref("Date/valueOf", "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`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) would be coerced to a string via [`Array.prototype.toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/getutcmonth/index.md | ---
title: Date.prototype.getUTCMonth()
slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCMonth
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getUTCMonth
---
{{JSRef}}
The **`getUTCMonth()`** method of {{jsxref("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).
{{EmbedInteractiveExample("pages/js/date-getutcmonth.html")}}
## Syntax
```js-nolint
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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## 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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getMonth()")}}
- {{jsxref("Date.prototype.setUTCMonth()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/setyear/index.md | ---
title: Date.prototype.setYear()
slug: Web/JavaScript/Reference/Global_Objects/Date/setYear
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.Date.setYear
---
{{JSRef}} {{Deprecated_Header}}
The **`setYear()`** method of {{jsxref("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 {{jsxref("Date/setFullYear", "setFullYear()")}} method sets year values — and in some cases, also different from how `new Date()` and {{jsxref("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 {{jsxref("Date.parse()")}}).
- {{jsxref("Date/setFullYear", "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 {{jsxref("Date/setFullYear", "setFullYear()")}} method.
## Syntax
```js-nolint
setYear(yearValue)
```
### Parameters
- `yearValue`
- : An integer.
### Return value
Changes the {{jsxref("Date")}} object in place, and returns its new [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). If `yearValue` is `NaN` (or other values that get [coerced](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to `NaN`, such as `undefined`), the date is set to [Invalid Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Date.prototype.setYear` in `core-js`](https://github.com/zloirock/core-js#ecmascript-date)
- {{jsxref("Date.prototype.getFullYear()")}}
- {{jsxref("Date.prototype.getUTCFullYear()")}}
- {{jsxref("Date.prototype.setFullYear()")}}
- {{jsxref("Date.prototype.setUTCFullYear()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/tolocalestring/index.md | ---
title: Date.prototype.toLocaleString()
slug: Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.toLocaleString
---
{{JSRef}}
The **`toLocaleString()`** method of {{jsxref("Date")}} instances returns a string with a language-sensitive representation of this date in the local timezone. In implementations with [`Intl.DateTimeFormat` API](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) 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 {{jsxref("Intl.DateTimeFormat")}} object and use its {{jsxref("Intl/DateTimeFormat/format", "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.
{{EmbedInteractiveExample("pages/js/date-tolocalestring.html")}}
## Syntax
```js-nolint
toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)
```
### Parameters
The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.
In implementations that support the [`Intl.DateTimeFormat` API](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/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_inline}}
- : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#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_inline}}
- : An object adjusting the output format. Corresponds to the [`options`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `weekday`, `year`, `month`, `day`, `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `year`, `month`, `day`, `hour`, `minute`, `second` will be set to `"numeric"`.
In implementations without `Intl.DateTimeFormat` support, this parameter is ignored.
See the [`Intl.DateTimeFormat()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them.
### Return value
A string representing the given date according to language-specific conventions.
In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`.
> **Note:** Most of the time, the formatting returned by `toLocaleString()` is consistent. However, the output may vary with time, language, and implementation — output variations are by design and allowed by the specification. You should not compare the results of `toLocaleString()` to static values.
## Examples
### Using toLocaleString()
Basic use of this method without specifying a `locale` returns a formatted string in the default locale and with default options.
```js
const date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));
// toLocaleString() without arguments depends on the
// implementation, the default locale, and the default time zone
console.log(date.toLocaleString());
// "12/11/2012, 7:00:00 PM" if run in en-US locale with time zone America/Los_Angeles
```
### Checking for support for locales and options parameters
The `locales` and `options` parameters may not be supported in all implementations, because support for the internationalization API is optional, and some systems may not have the necessary data. For implementations without internationalization support, `toLocaleString()` always uses the system's locale, which may not be what you want. Because any implementation that supports the `locales` and `options` parameters must support the {{jsxref("Intl")}} API, you can check the existence of the latter for support:
```js
function toLocaleStringSupportsLocales() {
return (
typeof Intl === "object" &&
!!Intl &&
typeof Intl.DateTimeFormat === "function"
);
}
```
### Using locales
This example shows some of the variations in localized date and time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:
```js
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// Formats below assume the local time zone of the locale;
// America/Los_Angeles for the US
// US English uses month-day-year order and 12-hour time with AM/PM
console.log(date.toLocaleString("en-US"));
// "12/19/2012, 7:00:00 PM"
// British English uses day-month-year order and 24-hour time without AM/PM
console.log(date.toLocaleString("en-GB"));
// "20/12/2012 03:00:00"
// Korean uses year-month-day order and 12-hour time with AM/PM
console.log(date.toLocaleString("ko-KR"));
// "2012. 12. 20. 오후 12:00:00"
// Arabic in most Arabic-speaking countries uses Eastern Arabic numerals
console.log(date.toLocaleString("ar-EG"));
// "٢٠/١٢/٢٠١٢ ٥:٠٠:٠٠ ص"
// For Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(date.toLocaleString("ja-JP-u-ca-japanese"));
// "24/12/20 12:00:00"
// When requesting a language that may not be supported, such as
// Balinese, include a fallback language (in this case, Indonesian)
console.log(date.toLocaleString(["ban", "id"]));
// "20/12/2012 11.00.00"
```
### Using options
The results provided by `toLocaleString()` can be customized using the `options` parameter:
```js
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// Request a weekday along with a long date
const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
console.log(date.toLocaleString("de-DE", options));
// "Donnerstag, 20. Dezember 2012"
// An application may want to use UTC and make that visible
options.timeZone = "UTC";
options.timeZoneName = "short";
console.log(date.toLocaleString("en-US", options));
// "Thursday, December 20, 2012, GMT"
// Sometimes even the US needs 24-hour time
console.log(date.toLocaleString("en-US", { hour12: false }));
// "12/19/2012, 19:00:00"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DateTimeFormat")}}
- {{jsxref("Date.prototype.toLocaleDateString()")}}
- {{jsxref("Date.prototype.toLocaleTimeString()")}}
- {{jsxref("Date.prototype.toString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/getyear/index.md | ---
title: Date.prototype.getYear()
slug: Web/JavaScript/Reference/Global_Objects/Date/getYear
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.Date.getYear
---
{{JSRef}} {{Deprecated_Header}}
The **`getYear()`** method of {{jsxref("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 {{jsxref("Date/getFullYear", "getFullYear()")}} method.
## Syntax
```js-nolint
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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
- 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 {{jsxref("Date/getFullYear", "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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Date.prototype.getYear` in `core-js`](https://github.com/zloirock/core-js#ecmascript-date)
- {{jsxref("Date.prototype.getFullYear()")}}
- {{jsxref("Date.prototype.getUTCFullYear()")}}
- {{jsxref("Date.prototype.setYear()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/toisostring/index.md | ---
title: Date.prototype.toISOString()
slug: Web/JavaScript/Reference/Global_Objects/Date/toISOString
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.toISOString
---
{{JSRef}}
The **`toISOString()`** method of {{jsxref("Date")}} instances returns a string representing this date in the [date time string format](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format), a _simplified_ format based on [ISO 8601](https://en.wikipedia.org/wiki/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`.
{{EmbedInteractiveExample("pages/js/date-toisostring.html")}}
## Syntax
```js-nolint
toISOString()
```
### Parameters
None.
### Return value
A string representing the given date in the [date time string format](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format) according to universal time. It's the same format as the one required to be recognized by {{jsxref("Date.parse()")}}.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) 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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.toLocaleDateString()")}}
- {{jsxref("Date.prototype.toString()")}}
- {{jsxref("Date.prototype.toUTCString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/getutcday/index.md | ---
title: Date.prototype.getUTCDay()
slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCDay
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getUTCDay
---
{{JSRef}}
The **`getUTCDay()`** method of {{jsxref("Date")}} instances returns the day of the week for this date according to universal time, where 0 represents Sunday.
{{EmbedInteractiveExample("pages/js/date-getutcday.html")}}
## Syntax
```js-nolint
getUTCDay()
```
### Parameters
None.
### Return value
An integer corresponding to the day of the week for the given date according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Returns `NaN` if the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Examples
### Using getUTCDay()
The following example assigns the weekday portion of the current date to the variable `weekday`.
```js
const today = new Date();
const weekday = today.getUTCDay();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCDate()")}}
- {{jsxref("Date.prototype.getDay()")}}
- {{jsxref("Date.prototype.setUTCDate()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/tojson/index.md | ---
title: Date.prototype.toJSON()
slug: Web/JavaScript/Reference/Global_Objects/Date/toJSON
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.toJSON
---
{{JSRef}}
The **`toJSON()`** method of {{jsxref("Date")}} instances returns a string representing this date in the same ISO format as {{jsxref("Date/toISOString", "toISOString()")}}.
{{EmbedInteractiveExample("pages/js/date-tojson.html")}}
## Syntax
```js-nolint
toJSON()
```
### Parameters
None.
### Return value
A string representing the given date in the [date time string format](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format) according to universal time, or `null` when the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). For valid dates, the return value is the same as that of {{jsxref("Date/toISOString", "toISOString()")}}.
## Description
The `toJSON()` method is automatically called by {{jsxref("JSON.stringify()")}} when a `Date` object is stringified. This method is generally intended to, by default, usefully serialize {{jsxref("Date")}} objects during [JSON](/en-US/docs/Glossary/JSON) serialization, which can then be deserialized using the {{jsxref("Date/Date", "Date()")}} constructor as the reviver of {{jsxref("JSON.parse()")}}.
The method first attempts to convert its `this` value [to a primitive](/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive) (with `"number"` as hint), {{jsxref("Object/valueOf", "valueOf()")}}, and {{jsxref("Object/toString", "toString()")}} methods, in that order. If the result is a [non-finite](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite) number, `null` is returned. (This generally corresponds to an invalid date, whose {{jsxref("Date/valueOf", "valueOf()")}} returns {{jsxref("NaN")}}.) Otherwise, if the converted primitive is not a number or is a finite number, the return value of {{jsxref("Date/toISOString", "this.toISOString()")}} is returned.
Note that the method does not check whether the `this` value is a valid {{jsxref("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 {{jsxref("Date/Date", "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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.toLocaleDateString()")}}
- {{jsxref("Date.prototype.toTimeString()")}}
- {{jsxref("Date.prototype.toUTCString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/gethours/index.md | ---
title: Date.prototype.getHours()
slug: Web/JavaScript/Reference/Global_Objects/Date/getHours
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getHours
---
{{JSRef}}
The **`getHours()`** method of {{jsxref("Date")}} instances returns the hours for this date according to local time.
{{EmbedInteractiveExample("pages/js/date-gethours.html", "shorter")}}
## Syntax
```js-nolint
getHours()
```
### Parameters
None.
### Return value
An integer, between 0 and 23, representing the hours for the given date according to local time. Returns `NaN` if the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Examples
### Using getHours()
The `hours` variable has value `23`, based on the value of the {{jsxref("Date")}} object `xmas95`.
```js
const xmas95 = new Date("1995-12-25T23:15:30");
const hours = xmas95.getHours();
console.log(hours); // 23
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCHours()")}}
- {{jsxref("Date.prototype.setHours()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/sethours/index.md | ---
title: Date.prototype.setHours()
slug: Web/JavaScript/Reference/Global_Objects/Date/setHours
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.setHours
---
{{JSRef}}
The **`setHours()`** method of {{jsxref("Date")}} instances changes the hours, minutes, seconds, and/or milliseconds for this date according to local time.
{{EmbedInteractiveExample("pages/js/date-sethours.html")}}
## Syntax
```js-nolint
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_inline}}
- : An integer between 0 and 59 representing the minutes.
- `secondsValue` {{optional_inline}}
- : An integer between 0 and 59 representing the seconds. If you specify `secondsValue`, you must also specify `minutesValue`.
- `msValue` {{optional_inline}}
- : An integer between 0 and 999 representing the milliseconds. If you specify `msValue`, you must also specify `minutesValue` and `secondsValue`.
### Return value
Changes the {{jsxref("Date")}} object in place, and returns its new [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). If a parameter is `NaN` (or other values that get [coerced](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to `NaN`, such as `undefined`), the date is set to [Invalid Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_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 {{jsxref("Date/getMinutes", "getMinutes()")}}, {{jsxref("Date/getSeconds", "getSeconds()")}}, and {{jsxref("Date/getMilliseconds", "getMilliseconds()")}} are used.
If a parameter you specify is outside of the expected range, other parameters and the date information in the {{jsxref("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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getHours()")}}
- {{jsxref("Date.prototype.setUTCHours()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/setmilliseconds/index.md | ---
title: Date.prototype.setMilliseconds()
slug: Web/JavaScript/Reference/Global_Objects/Date/setMilliseconds
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.setMilliseconds
---
{{JSRef}}
The **`setMilliseconds()`** method of {{jsxref("Date")}} instances changes the milliseconds for this date according to local time.
{{EmbedInteractiveExample("pages/js/date-setmilliseconds.html")}}
## Syntax
```js-nolint
setMilliseconds(millisecondsValue)
```
### Parameters
- `millisecondsValue`
- : An integer between 0 and 999 representing the milliseconds.
### Return value
Changes the {{jsxref("Date")}} object in place, and returns its new [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). If `millisecondsValue` is `NaN` (or other values that get [coerced](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to `NaN`, such as `undefined`), the date is set to [Invalid Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) and `NaN` is returned.
## Description
If you specify a number outside the expected range, the date information in the {{jsxref("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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getMilliseconds()")}}
- {{jsxref("Date.prototype.setUTCMilliseconds()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/index.md | ---
title: Object
slug: Web/JavaScript/Reference/Global_Objects/Object
page-type: javascript-class
browser-compat: javascript.builtins.Object
---
{{JSRef}}
The **`Object`** type represents one of [JavaScript's data types](/en-US/docs/Web/JavaScript/Data_structures). It is used to store various keyed collections and more complex entities. Objects can be created using the {{jsxref("Object/Object", "Object()")}} constructor or the [object initializer / literal syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer).
## Description
Nearly all [objects](/en-US/docs/Web/JavaScript/Data_structures#objects) in JavaScript are instances of `Object`; a typical object inherits properties (including methods) from `Object.prototype`, although these properties may be shadowed (a.k.a. overridden). The only objects that don't inherit from `Object.prototype` are those with [`null` prototype](#null-prototype_objects), or descended from other `null` prototype objects.
Changes to the `Object.prototype` object are seen by **all** objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain. This provides a very powerful although potentially dangerous mechanism to override or extend object behavior. To make it more secure, `Object.prototype` is the only object in the core JavaScript language that has [immutable prototype](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf#description) — the prototype of `Object.prototype` is always `null` and not changeable.
### Object prototype properties
You should avoid calling any `Object.prototype` method directly from the instance, especially those that are not intended to be polymorphic (i.e. only its initial behavior makes sense and no descending object could override it in a meaningful way). All objects descending from `Object.prototype` may define a custom own property that has the same name, but with entirely different semantics from what you expect. Furthermore, these properties are not inherited by [`null`-prototype objects](#null-prototype_objects). All modern JavaScript utilities for working with objects are [static](#static_methods). More specifically:
- [`valueOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf), [`toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString), and [`toLocaleString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toLocaleString) exist to be polymorphic and you should expect the object to define its own implementation with sensible behaviors, so you can call them as instance methods. However, `valueOf()` and `toString()` are usually implicitly called through [type conversion](/en-US/docs/Web/JavaScript/Data_structures#type_coercion) and you don't need to call them yourself in your code.
- [`__defineGetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__), [`__defineSetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__), [`__lookupGetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__), and [`__lookupSetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__) are deprecated and should not be used. Use the static alternatives {{jsxref("Object.defineProperty()")}} and {{jsxref("Object.getOwnPropertyDescriptor()")}} instead.
- The [`__proto__`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto) property is deprecated and should not be used. The {{jsxref("Object.getPrototypeOf()")}} and {{jsxref("Object.setPrototypeOf()")}} alternatives are static methods.
- The [`propertyIsEnumerable()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable) and [`hasOwnProperty()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) methods can be replaced with the {{jsxref("Object.getOwnPropertyDescriptor()")}} and {{jsxref("Object.hasOwn()")}} static methods, respectively.
- The [`isPrototypeOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf) method can usually be replaced with [`instanceof`](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof), if you are checking the `prototype` property of a constructor.
In case where a semantically equivalent static method doesn't exist, or if you really want to use the `Object.prototype` method, you should directly [`call()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) the `Object.prototype` method on your target object instead, to prevent the object from having an overriding property that produces unexpected results.
```js
const obj = {
foo: 1,
// You should not define such a method on your own object,
// but you may not be able to prevent it from happening if
// you are receiving the object from external input
propertyIsEnumerable() {
return false;
},
};
obj.propertyIsEnumerable("foo"); // false; unexpected result
Object.prototype.propertyIsEnumerable.call(obj, "foo"); // true; expected result
```
### Deleting a property from an object
There isn't any method in an Object itself to delete its own properties (such as {{jsxref("Map.prototype.delete()")}}). To do so, one must use the {{jsxref("Operators/delete", "delete")}} operator.
### null-prototype objects
Almost all objects in JavaScript ultimately inherit from `Object.prototype` (see [inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)). However, you may create `null`-prototype objects using [`Object.create(null)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) or the [object initializer syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) with `__proto__: null` (note: the `__proto__` key in object literals is different from the deprecated [`Object.prototype.__proto__`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto) property). You can also change the prototype of an existing object to `null` by calling [`Object.setPrototypeOf(obj, null)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf).
```js
const obj = Object.create(null);
const obj2 = { __proto__: null };
```
An object with a `null` prototype can behave in unexpected ways, because it doesn't inherit any object methods from `Object.prototype`. This is especially true when debugging, since common object-property converting/detecting utility functions may generate errors, or lose information (especially if using silent error-traps that ignore errors).
For example, the lack of [`Object.prototype.toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString) often makes debugging intractable:
```js
const normalObj = {}; // create a normal object
const nullProtoObj = Object.create(null); // create an object with "null" prototype
console.log(`normalObj is: ${normalObj}`); // shows "normalObj is: [object Object]"
console.log(`nullProtoObj is: ${nullProtoObj}`); // throws error: Cannot convert object to primitive value
alert(normalObj); // shows [object Object]
alert(nullProtoObj); // throws error: Cannot convert object to primitive value
```
Other methods will fail as well.
```js
normalObj.valueOf(); // shows {}
nullProtoObj.valueOf(); // throws error: nullProtoObj.valueOf is not a function
normalObj.hasOwnProperty("p"); // shows "true"
nullProtoObj.hasOwnProperty("p"); // throws error: nullProtoObj.hasOwnProperty is not a function
normalObj.constructor; // shows "Object() { [native code] }"
nullProtoObj.constructor; // shows "undefined"
```
We can add the `toString` method back to the null-prototype object by assigning it one:
```js
nullProtoObj.toString = Object.prototype.toString; // since new object lacks toString, add the original generic one back
console.log(nullProtoObj.toString()); // shows "[object Object]"
console.log(`nullProtoObj is: ${nullProtoObj}`); // shows "nullProtoObj is: [object Object]"
```
Unlike normal objects, in which `toString()` is on the object's prototype, the `toString()` method here is an own property of `nullProtoObj`. This is because `nullProtoObj` has no (`null`) prototype.
You can also revert a null-prototype object back to an ordinary object using [`Object.setPrototypeOf(nullProtoObj, Object.prototype)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf).
In practice, objects with `null` prototype are usually used as a cheap substitute for [maps](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map). The presence of `Object.prototype` properties will cause some bugs:
```js
const ages = { alice: 18, bob: 27 };
function hasPerson(name) {
return name in ages;
}
function getAge(name) {
return ages[name];
}
hasPerson("hasOwnProperty"); // true
getAge("toString"); // [Function: toString]
```
Using a null-prototype object removes this hazard without introducing too much complexity to the `hasPerson` and `getAge` functions:
```js
const ages = Object.create(null, {
alice: { value: 18, enumerable: true },
bob: { value: 27, enumerable: true },
});
hasPerson("hasOwnProperty"); // false
getAge("toString"); // undefined
```
In such case, the addition of any method should be done cautiously, as they can be confused with the other key-value pairs stored as data.
Making your object not inherit from `Object.prototype` also prevents prototype pollution attacks. If a malicious script adds a property to `Object.prototype`, it will be accessible on every object in your program, except objects that have null prototype.
```js
const user = {};
// A malicious script:
Object.prototype.authenticated = true;
// Unexpectedly allowing unauthenticated user to pass through
if (user.authenticated) {
// access confidential data
}
```
JavaScript also has built-in APIs that produce `null`-prototype objects, especially those that use objects as ad hoc key-value collections. For example:
- The return value of {{jsxref("Object.groupBy()")}}
- The `groups` and `indices.groups` properties of the result of {{jsxref("RegExp.prototype.exec()")}}
- [`Array.prototype[@@unscopables]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@unscopables) (all `@@unscopables` objects should have `null`-prototype)
- [`import.meta`](/en-US/docs/Web/JavaScript/Reference/Operators/import.meta)
- Module namespace objects, obtained through [`import * as ns from "module";`](/en-US/docs/Web/JavaScript/Reference/Statements/import#namespace_import) or [`import()`](/en-US/docs/Web/JavaScript/Reference/Operators/import)
The term "`null`-prototype object" often also includes any object without `Object.prototype` in its prototype chain. Such objects can be created with [`extends null`](/en-US/docs/Web/JavaScript/Reference/Classes/extends#extending_null) when using classes.
### Object coercion
Many built-in operations that expect objects first coerce their arguments to objects. [The operation](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-toobject) can be summarized as follows:
- Objects are returned as-is.
- [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) and [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) throw a {{jsxref("TypeError")}}.
- {{jsxref("Number")}}, {{jsxref("String")}}, {{jsxref("Boolean")}}, {{jsxref("Symbol")}}, {{jsxref("BigInt")}} primitives are wrapped into their corresponding object wrappers.
There are two ways to achieve nearly the same effect in JavaScript.
- {{jsxref("Object.prototype.valueOf()")}}: `Object.prototype.valueOf.call(x)` does exactly the object coercion steps explained above to convert `x`.
- The {{jsxref("Object/Object", "Object()")}} function: `Object(x)` uses the same algorithm to convert `x`, except that `undefined` and `null` don't throw a {{jsxref("TypeError")}}, but return a plain object.
Places that use object coercion include:
- The `object` parameter of [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loops.
- The `this` value of {{jsxref("Array")}} methods.
- Parameters of `Object` methods such as {{jsxref("Object.keys()")}}.
- Auto-boxing when a property is accessed on a primitive value, since primitives do not have properties.
- The [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) value when calling a non-strict function. Primitives are boxed while `null` and `undefined` are replaced with the [global object](/en-US/docs/Glossary/Global_object).
Unlike [conversion to primitives](/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion), the object coercion process itself is not observable in any way, since it doesn't invoke custom code like `toString` or `valueOf` methods.
## Constructor
- {{jsxref("Object/Object", "Object()")}}
- : Turns the input into an object.
## Static methods
- {{jsxref("Object.assign()")}}
- : Copies the values of all enumerable own properties from one or more source objects to a target object.
- {{jsxref("Object.create()")}}
- : Creates a new object with the specified prototype object and properties.
- {{jsxref("Object.defineProperties()")}}
- : Adds the named properties described by the given descriptors to an object.
- {{jsxref("Object.defineProperty()")}}
- : Adds the named property described by a given descriptor to an object.
- {{jsxref("Object.entries()")}}
- : Returns an array containing all of the `[key, value]` pairs of a given object's **own** enumerable string properties.
- {{jsxref("Object.freeze()")}}
- : Freezes an object. Other code cannot delete or change its properties.
- {{jsxref("Object.fromEntries()")}}
- : Returns a new object from an iterable of `[key, value]` pairs. (This is the reverse of {{jsxref("Object.entries")}}).
- {{jsxref("Object.getOwnPropertyDescriptor()")}}
- : Returns a property descriptor for a named property on an object.
- {{jsxref("Object.getOwnPropertyDescriptors()")}}
- : Returns an object containing all own property descriptors for an object.
- {{jsxref("Object.getOwnPropertyNames()")}}
- : Returns an array containing the names of all of the given object's **own** enumerable and non-enumerable properties.
- {{jsxref("Object.getOwnPropertySymbols()")}}
- : Returns an array of all symbol properties found directly upon a given object.
- {{jsxref("Object.getPrototypeOf()")}}
- : Returns the prototype (internal `[[Prototype]]` property) of the specified object.
- {{jsxref("Object.groupBy()")}}
- : Groups the elements of a given iterable according to the string values returned by a provided callback function. The returned object has separate properties for each group, containing arrays with the elements in the group.
- {{jsxref("Object.hasOwn()")}}
- : Returns `true` if the specified object has the indicated property as its _own_ property, or `false` if the property is inherited or does not exist.
- {{jsxref("Object.is()")}}
- : Compares if two values are the same value. Equates all `NaN` values (which differs from both `IsLooselyEqual` used by [`==`](/en-US/docs/Web/JavaScript/Reference/Operators/Equality) and `IsStrictlyEqual` used by [`===`](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality)).
- {{jsxref("Object.isExtensible()")}}
- : Determines if extending of an object is allowed.
- {{jsxref("Object.isFrozen()")}}
- : Determines if an object was frozen.
- {{jsxref("Object.isSealed()")}}
- : Determines if an object is sealed.
- {{jsxref("Object.keys()")}}
- : Returns an array containing the names of all of the given object's **own** enumerable string properties.
- {{jsxref("Object.preventExtensions()")}}
- : Prevents any extensions of an object.
- {{jsxref("Object.seal()")}}
- : Prevents other code from deleting properties of an object.
- {{jsxref("Object.setPrototypeOf()")}}
- : Sets the object's prototype (its internal `[[Prototype]]` property).
- {{jsxref("Object.values()")}}
- : Returns an array containing the values that correspond to all of a given object's **own** enumerable string properties.
## Instance properties
These properties are defined on `Object.prototype` and shared by all `Object` instances.
- [`Object.prototype.__proto__`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto) {{deprecated_inline}}
- : Points to the object which was used as prototype when the object was instantiated.
- {{jsxref("Object.prototype.constructor")}}
- : The constructor function that created the instance object. For plain `Object` instances, the initial value is the {{jsxref("Object/Object", "Object")}} constructor. Instances of other constructors each inherit the `constructor` property from their respective `Constructor.prototype` object.
## Instance methods
- [`Object.prototype.__defineGetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__) {{deprecated_inline}}
- : Associates a function with a property that, when accessed, executes that function and returns its return value.
- [`Object.prototype.__defineSetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__) {{deprecated_inline}}
- : Associates a function with a property that, when set, executes that function which modifies the property.
- [`Object.prototype.__lookupGetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__) {{deprecated_inline}}
- : Returns the function bound as a getter to the specified property.
- [`Object.prototype.__lookupSetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__) {{deprecated_inline}}
- : Returns the function bound as a setter to the specified property.
- {{jsxref("Object.prototype.hasOwnProperty()")}}
- : Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.
- {{jsxref("Object.prototype.isPrototypeOf()")}}
- : Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.
- {{jsxref("Object.prototype.propertyIsEnumerable()")}}
- : Returns a boolean indicating whether the specified property is the object's [enumerable own](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) property.
- {{jsxref("Object.prototype.toLocaleString()")}}
- : Calls {{jsxref("Object/toString", "toString()")}}.
- {{jsxref("Object.prototype.toString()")}}
- : Returns a string representation of the object.
- {{jsxref("Object.prototype.valueOf()")}}
- : Returns the primitive value of the specified object.
## Examples
### Constructing empty objects
The following example creates empty objects using the `new` keyword with different arguments:
```js
const o1 = new Object();
const o2 = new Object(undefined);
const o3 = new Object(null);
```
### Using Object() constructor to turn primitives into an Object of their respective type
You can use the {{jsxref("Object/Object", "Object()")}} constructor to create an object wrapper of a primitive value.
The following examples create variables `o1` and `o2` which are objects storing {{jsxref("Boolean")}} and {{jsxref("BigInt")}} values:
```js
// Equivalent to const o1 = new Boolean(true)
const o1 = new Object(true);
// No equivalent because BigInt() can't be called as a constructor,
// and calling it as a regular function won't create an object
const o2 = new Object(1n);
```
### Object prototypes
When altering the behavior of existing `Object.prototype` methods, consider injecting code by wrapping your extension before or after the existing logic. For example, this (untested) code will pre-conditionally execute custom logic before the built-in logic or someone else's extension is executed.
When modifying prototypes with hooks, pass `this` and the arguments (the call state) to the current behavior by calling `apply()` on the function. This pattern can be used for any prototype, such as `Node.prototype`, `Function.prototype`, etc.
```js
const current = Object.prototype.valueOf;
// Since my property "-prop-value" is cross-cutting and isn't always
// on the same prototype chain, I want to modify Object.prototype:
Object.prototype.valueOf = function (...args) {
if (Object.hasOwn(this, "-prop-value")) {
return this["-prop-value"];
} else {
// It doesn't look like one of my objects, so let's fall back on
// the default behavior by reproducing the current behavior as best we can.
// The apply behaves like "super" in some other languages.
// Even though valueOf() doesn't take arguments, some other hook may.
return current.apply(this, args);
}
};
```
> **Warning:** Modifying the `prototype` property of any built-in constructor is considered a bad practice and risks forward compatibility.
You can read more about prototypes in [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/propertyisenumerable/index.md | ---
title: Object.prototype.propertyIsEnumerable()
slug: Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable
page-type: javascript-instance-method
browser-compat: javascript.builtins.Object.propertyIsEnumerable
---
{{JSRef}}
The **`propertyIsEnumerable()`** method of {{jsxref("Object")}} instances returns a boolean indicating whether the specified property is this object's [enumerable own](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) property.
{{EmbedInteractiveExample("pages/js/object-prototype-propertyisenumerable.html", "taller")}}
## Syntax
```js-nolint
propertyIsEnumerable(prop)
```
### Parameters
- `prop`
- : The name of the property to test. Can be a string or a {{jsxref("Symbol")}}.
### Return value
A boolean value indicating whether the specified property is enumerable and is the object's own property.
## Description
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `propertyIsEnumerable()` method. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns `false`.
This method is equivalent to [`Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor).
## Examples
### Using propertyIsEnumerable()
The following example shows the use of `propertyIsEnumerable()` on objects and arrays.
```js
const o = {};
const a = [];
o.prop = "is enumerable";
a[0] = "is enumerable";
o.propertyIsEnumerable("prop"); // true
a.propertyIsEnumerable(0); // true
```
### User-defined vs. built-in objects
Most built-in properties are non-enumerable by default, while user-created object properties are often enumerable, unless explicitly designated otherwise.
```js
const a = ["is enumerable"];
a.propertyIsEnumerable(0); // true
a.propertyIsEnumerable("length"); // false
Math.propertyIsEnumerable("random"); // false
globalThis.propertyIsEnumerable("Math"); // false
```
### Direct vs. inherited properties
Only enumerable own properties cause `propertyIsEnumerable()` to return `true`, although all enumerable properties, including inherited ones, are visited by the [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loop.
```js
const o1 = {
enumerableInherited: "is enumerable",
};
Object.defineProperty(o1, "nonEnumerableInherited", {
value: "is non-enumerable",
enumerable: false,
});
const o2 = {
// o1 is the prototype of o2
__proto__: o1,
enumerableOwn: "is enumerable",
};
Object.defineProperty(o2, "nonEnumerableOwn", {
value: "is non-enumerable",
enumerable: false,
});
o2.propertyIsEnumerable("enumerableInherited"); // false
o2.propertyIsEnumerable("nonEnumerableInherited"); // false
o2.propertyIsEnumerable("enumerableOwn"); // true
o2.propertyIsEnumerable("nonEnumerableOwn"); // false
```
### Testing symbol properties
{{jsxref("Symbol")}} properties are also supported by `propertyIsEnumerable()`. Note that most enumeration methods only visit string properties; enumerability of symbol properties is only useful when using {{jsxref("Object.assign()")}} or [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). For more information, see [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties).
```js
const sym = Symbol("enumerable");
const sym2 = Symbol("non-enumerable");
const o = {
[sym]: "is enumerable",
};
Object.defineProperty(o, sym2, {
value: "is non-enumerable",
enumerable: false,
});
o.propertyIsEnumerable(sym); // true
o.propertyIsEnumerable(sym2); // false
```
### Usage with null-prototype objects
Because `null`-prototype objects do not inherit from `Object.prototype`, they do not inherit the `propertyIsEnumerable()` method. You must call `Object.prototype.propertyIsEnumerable` with the object as `this` instead.
```js
const o = {
__proto__: null,
enumerableOwn: "is enumerable",
};
o.propertyIsEnumerable("enumerableOwn"); // TypeError: o.propertyIsEnumerable is not a function
Object.prototype.propertyIsEnumerable.call(o, "enumerableOwn"); // true
```
Alternatively, you may use {{jsxref("Object.getOwnPropertyDescriptor()")}} instead, which also helps to distinguish between non-existent properties and actually non-enumerable properties.
```js
const o = {
__proto__: null,
enumerableOwn: "is enumerable",
};
Object.getOwnPropertyDescriptor(o, "enumerableOwn")?.enumerable; // true
Object.getOwnPropertyDescriptor(o, "nonExistent")?.enumerable; // undefined
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
- {{jsxref("Statements/for...in", "for...in")}}
- {{jsxref("Object.keys()")}}
- {{jsxref("Object.defineProperty()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/issealed/index.md | ---
title: Object.isSealed()
slug: Web/JavaScript/Reference/Global_Objects/Object/isSealed
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.isSealed
---
{{JSRef}}
The **`Object.isSealed()`** static method determines if an object is
sealed.
{{EmbedInteractiveExample("pages/js/object-issealed.html")}}
## Syntax
```js-nolint
Object.isSealed(obj)
```
### Parameters
- `obj`
- : The object which should be checked.
### Return value
A {{jsxref("Boolean")}} indicating whether or not the given object is sealed.
## Description
Returns `true` if the object is sealed, otherwise `false`. An
object is sealed if it is not {{jsxref("Object/isExtensible", "extensible", "", 1)}} and
if all its properties are non-configurable and therefore not removable (but not
necessarily non-writable).
## Examples
### Using Object.isSealed
```js
// Objects aren't sealed by default.
const empty = {};
Object.isSealed(empty); // false
// If you make an empty object non-extensible,
// it is vacuously sealed.
Object.preventExtensions(empty);
Object.isSealed(empty); // true
// The same is not true of a non-empty object,
// unless its properties are all non-configurable.
const hasProp = { fee: "fie foe fum" };
Object.preventExtensions(hasProp);
Object.isSealed(hasProp); // false
// But make them all non-configurable
// and the object becomes sealed.
Object.defineProperty(hasProp, "fee", {
configurable: false,
});
Object.isSealed(hasProp); // true
// The easiest way to seal an object, of course,
// is Object.seal.
const sealed = {};
Object.seal(sealed);
Object.isSealed(sealed); // true
// A sealed object is, by definition, non-extensible.
Object.isExtensible(sealed); // false
// A sealed object might be frozen,
// but it doesn't have to be.
Object.isFrozen(sealed); // true
// (all properties also non-writable)
const s2 = Object.seal({ p: 3 });
Object.isFrozen(s2); // false
// ('p' is still writable)
const s3 = Object.seal({
get p() {
return 0;
},
});
Object.isFrozen(s3); // true
// (only configurability matters for accessor properties)
```
### Non-object argument
In ES5, if the argument to this method is not an object (a primitive), then it will cause a {{jsxref("TypeError")}}. In ES2015, it will return `true` without any errors if a non-object argument is passed, since primitives are, by definition, immutable.
```js
Object.isSealed(1);
// TypeError: 1 is not an object (ES5 code)
Object.isSealed(1);
// true (ES2015 code)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Object.seal()")}}
- {{jsxref("Object.preventExtensions()")}}
- {{jsxref("Object.isExtensible()")}}
- {{jsxref("Object.freeze()")}}
- {{jsxref("Object.isFrozen()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/groupby/index.md | ---
title: Object.groupBy()
slug: Web/JavaScript/Reference/Global_Objects/Object/groupBy
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.groupBy
---
{{JSRef}}
> **Note:** In some versions of some browsers, this method was implemented as the method `Array.prototype.group()`. Due to web compatibility issues, it is now implemented as a static method. Check the [browser compatibility table](#browser_compatibility) for details.
The **`Object.groupBy()`** static method groups the elements of a given iterable according to the string values returned by a provided callback function. The returned object has separate properties for each group, containing arrays with the elements in the group.
This method should be used when group names can be represented by strings. If you need to group elements using a key that is some arbitrary value, use {{jsxref("Map.groupBy()")}} instead.
<!-- {{EmbedInteractiveExample("pages/js/object-groupby.html")}} -->
## Syntax
```js-nolint
Object.groupBy(items, callbackFn)
```
### Parameters
- `items`
- : An [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an {{jsxref("Array")}}) whose elements will be grouped.
- `callbackFn`
- : A function to execute for each element in the iterable. It should return a value that can get coerced into a property key (string or [symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol)) indicating the group of the current element. The function is called with the following arguments:
- `element`
- : The current element being processed.
- `index`
- : The index of the current element being processed.
### Return value
A [`null`-prototype object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) with properties for all groups, each assigned to an array containing the elements of the associated group.
## Description
`Object.groupBy()` calls a provided `callbackFn` function once for each element in an iterable. The callback function should return a string or symbol (values that are neither type are [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion)) indicating the group of the associated element. The values returned by `callbackFn` are used as keys for the object returned by `Map.groupBy()`. Each key has an associated array containing all the elements for which the callback returned the same value.
The elements in the returned object and the original iterable are the same (not {{Glossary("deep copy", "deep copies")}}). Changing the internal structure of the elements will be reflected in both the original iterable and the returned object.
## Examples
### Using Object.groupBy()
First we define an array containing objects representing an inventory of different foodstuffs. Each food has a `type` and a `quantity`.
```js
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
{ name: "fish", type: "meat", quantity: 22 },
];
```
The code below groups the elements by the value of their `type` property.
```js
const result = Object.groupBy(inventory, ({ type }) => type);
/* Result is:
{
vegetables: [
{ name: 'asparagus', type: 'vegetables', quantity: 5 },
],
fruit: [
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "cherries", type: "fruit", quantity: 5 }
],
meat: [
{ name: "goat", type: "meat", quantity: 23 },
{ name: "fish", type: "meat", quantity: 22 }
]
}
*/
```
The arrow function just returns the `type` of each array element each time it is called. Note that the function argument `{ type }` is a basic example of [object destructuring syntax for function arguments](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#unpacking_properties_from_objects_passed_as_a_function_parameter). This unpacks the `type` property of an object passed as a parameter, and assigns it to a variable named `type` in the body of the function.
This is a very succinct way to access the relevant values of elements within a function.
We can also create groups inferred from values in one or more properties of the elements. Below is a very similar example that puts the items into `ok` or `restock` groups based on the value of the `quantity` field.
```js
function myCallback({ quantity }) {
return quantity > 5 ? "ok" : "restock";
}
const result2 = Object.groupBy(inventory, myCallback);
/* Result is:
{
restock: [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "cherries", type: "fruit", quantity: 5 }
],
ok: [
{ name: "goat", type: "meat", quantity: 23 },
{ name: "fish", type: "meat", quantity: 22 }
]
}
*/
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.groupBy` in `core-js`](https://github.com/zloirock/core-js#array-grouping)
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array.prototype.reduce()")}}
- {{jsxref("Object.fromEntries()")}}
- {{jsxref("Map.groupBy()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/tostring/index.md | ---
title: Object.prototype.toString()
slug: Web/JavaScript/Reference/Global_Objects/Object/toString
page-type: javascript-instance-method
browser-compat: javascript.builtins.Object.toString
---
{{JSRef}}
The **`toString()`** method of {{jsxref("Object")}} instances returns a string representing this object. This method is meant to be overridden by derived objects for custom [type coercion](/en-US/docs/Web/JavaScript/Data_structures#type_coercion) logic.
{{EmbedInteractiveExample("pages/js/object-prototype-tostring.html")}}
## Syntax
```js-nolint
toString()
```
### Parameters
By default `toString()` takes no parameters. However, objects that inherit from `Object` may override it with their own implementations that do take parameters. For example, the [`Number.prototype.toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) and [`BigInt.prototype.toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/toString) methods take an optional `radix` parameter.
### Return value
A string representing the object.
## Description
JavaScript calls the `toString` method to [convert an object to a primitive value](/en-US/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `toString` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.
This method is called in priority by [string conversion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), but [numeric conversion](/en-US/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion) call `valueOf()` in priority. However, because the base [`valueOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf) method returns an object, the `toString()` method is usually called in the end, unless the object overrides `valueOf()`. For example, `+[1]` returns `1`, because its [`toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString) method returns `"1"`, which is then converted to a number.
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. When you create a custom object, you can override `toString()` to call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a [`@@toPrimitive`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion.
To use the base `Object.prototype.toString()` with an object that has it overridden (or to invoke it on `null` or `undefined`), you need to call {{jsxref("Function.prototype.call()")}} or {{jsxref("Function.prototype.apply()")}} on it, passing the object you want to inspect as the first parameter (called `thisArg`).
```js
const arr = [1, 2, 3];
arr.toString(); // "1,2,3"
Object.prototype.toString.call(arr); // "[object Array]"
```
`Object.prototype.toString()` returns `"[object Type]"`, where `Type` is the object type. If the object has a [`Symbol.toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property whose value is a string, that value will be used as the `Type`. Many built-in objects, including [`Map`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) and [`Symbol`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), have a `Symbol.toStringTag`. Some objects predating ES6 do not have `Symbol.toStringTag`, but have a special tag nonetheless. They include (the tag is the same as the type name given below):
- [`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
- [`Function`](/en-US/docs/Web/JavaScript/Reference/Functions) (anything whose [`typeof`](/en-US/docs/Web/JavaScript/Reference/Operators/typeof) returns `"function"`)
- [`Error`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
- [`Boolean`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)
- [`Number`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)
- [`String`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
- [`Date`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
- [`RegExp`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
The [`arguments`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments) object returns `"[object Arguments]"`. Everything else, including user-defined classes, unless with a custom `Symbol.toStringTag`, will return `"[object Object]"`.
`Object.prototype.toString()` invoked on [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) and {{jsxref("undefined")}} returns `[object Null]` and `[object Undefined]`, respectively.
## Examples
### Overriding toString for custom objects
You can create a function to be called in place of the default `toString()` method. The `toString()` function you create should return a string value. If it returns an object and the method is called implicitly during [type conversion](/en-US/docs/Web/JavaScript/Data_structures#type_coercion), then its result is ignored and the value of a related method, {{jsxref("Object/valueOf", "valueOf()")}}, is used instead, or a `TypeError` is thrown if none of these methods return a primitive.
The following code defines a `Dog` class.
```js
class Dog {
constructor(name, breed, color, sex) {
this.name = name;
this.breed = breed;
this.color = color;
this.sex = sex;
}
}
```
If you call the `toString()` method, either explicitly or implicitly, on an instance of `Dog`, it returns the default value inherited from {{jsxref("Object")}}:
```js
const theDog = new Dog("Gabby", "Lab", "chocolate", "female");
theDog.toString(); // "[object Object]"
`${theDog}`; // "[object Object]"
```
The following code overrides the default `toString()` method. This method generates a string containing the `name`, `breed`, `color`, and `sex` of the object.
```js
class Dog {
constructor(name, breed, color, sex) {
this.name = name;
this.breed = breed;
this.color = color;
this.sex = sex;
}
toString() {
return `Dog ${this.name} is a ${this.sex} ${this.color} ${this.breed}`;
}
}
```
With the preceding code in place, any time an instance of `Dog` is used in a string context, JavaScript automatically calls the `toString()` method.
```js
const theDog = new Dog("Gabby", "Lab", "chocolate", "female");
`${theDog}`; // "Dog Gabby is a female chocolate Lab"
```
### Using toString() to detect object class
`toString()` can be used with every object and (by default) allows you to get its class.
```js
const toString = Object.prototype.toString;
toString.call(new Date()); // [object Date]
toString.call(new String()); // [object String]
// Math has its Symbol.toStringTag
toString.call(Math); // [object Math]
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]
```
Using `toString()` in this way is unreliable; objects can change the behavior of `Object.prototype.toString()` by defining a {{jsxref("Symbol.toStringTag")}} property, leading to unexpected results. For example:
```js
const myDate = new Date();
Object.prototype.toString.call(myDate); // [object Date]
myDate[Symbol.toStringTag] = "myDate";
Object.prototype.toString.call(myDate); // [object myDate]
Date.prototype[Symbol.toStringTag] = "prototype polluted";
Object.prototype.toString.call(new Date()); // [object prototype polluted]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.prototype.toString` with `Symbol.toStringTag` support in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- {{jsxref("Object.prototype.valueOf()")}}
- {{jsxref("Number.prototype.toString()")}}
- {{jsxref("Symbol.toPrimitive")}}
- {{jsxref("Symbol.toStringTag")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/__definegetter__/index.md | ---
title: Object.prototype.__defineGetter__()
slug: Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.Object.defineGetter
---
{{JSRef}}{{Deprecated_Header}}
> **Note:** This feature is deprecated in favor of defining [getters](/en-US/docs/Web/JavaScript/Reference/Functions/get) using the [object initializer syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) or the {{jsxref("Object.defineProperty()")}} API. This method's behavior is only specified for web compatibility, and is not required to be implemented in any platform. It may not work everywhere.
The **`__defineGetter__()`** method of {{jsxref("Object")}} instances binds an object's property to a function to be called when that property is looked up.
## Syntax
```js-nolint
__defineGetter__(prop, func)
```
### Parameters
- `prop`
- : A string containing the name of the property that the getter `func` is bound to.
- `func`
- : A function to be bound to a lookup of the specified property.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `func` is not a function.
## Description
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `__defineGetter__()` method. This method allows a [getter](/en-US/docs/Web/JavaScript/Reference/Functions/get) to be defined on a pre-existing object. This is equivalent to [`Object.defineProperty(obj, prop, { get: func, configurable: true, enumerable: true })`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty), which means the property is enumerable and configurable, and any existing setter, if present, is preserved.
`__defineGetter__()` is defined in the spec as "normative optional", which means no implementation is required to implement this. However, all major browsers implement it, and due to its continued usage, it's unlikely to be removed. If a browser implements `__defineGetter__()`, it also needs to implement the [`__lookupGetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__), [`__lookupSetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__), and [`__defineSetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__) methods.
## Examples
### Using \_\_defineGetter\_\_()
```js
const o = {};
o.__defineGetter__("gimmeFive", function () {
return 5;
});
console.log(o.gimmeFive); // 5
```
### Defining a getter property in standard ways
You can use the `get` syntax to define a getter when the object is first initialized.
```js
const o = {
get gimmeFive() {
return 5;
},
};
console.log(o.gimmeFive); // 5
```
You may also use {{jsxref("Object.defineProperty()")}} to define a getter on an object after it's been created. Compared to `__defineGetter__()`, this method allows you to control the getter's enumerability and configurability, as well as defining [symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) properties. The `Object.defineProperty()` method also works with [`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), which don't inherit from `Object.prototype` and therefore don't have the `__defineGetter__()` method.
```js
const o = {};
Object.defineProperty(o, "gimmeFive", {
get() {
return 5;
},
configurable: true,
enumerable: true,
});
console.log(o.gimmeFive); // 5
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.prototype.__defineGetter__` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- [`Object.prototype.__defineSetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__)
- {{jsxref("Functions/get", "get")}}
- {{jsxref("Object.defineProperty()")}}
- [`Object.prototype.__lookupGetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__)
- [`Object.prototype.__lookupSetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__)
- [JS Guide: Defining Getters and Setters](/en-US/docs/Web/JavaScript/Guide/Working_with_objects#defining_getters_and_setters)
- [Firefox bug 647423](https://bugzil.la/647423)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/create/index.md | ---
title: Object.create()
slug: Web/JavaScript/Reference/Global_Objects/Object/create
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.create
---
{{JSRef}}
The **`Object.create()`** static method creates a new object, using an existing object as the prototype of the newly created object.
{{EmbedInteractiveExample("pages/js/object-create.html", "taller")}}
## Syntax
```js-nolint
Object.create(proto)
Object.create(proto, propertiesObject)
```
### Parameters
- `proto`
- : The object which should be the prototype of the newly-created object.
- `propertiesObject` {{optional_inline}}
- : If specified and not {{jsxref("undefined")}}, an object whose [enumerable own properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of {{jsxref("Object.defineProperties()")}}.
### Return value
A new object with the specified prototype object and properties.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `proto` is neither [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) nor an {{jsxref("Object")}}.
## Examples
### Classical inheritance with Object.create()
Below is an example of how to use `Object.create()` to achieve classical inheritance. This is for a single inheritance, which is all that JavaScript supports.
```js
// Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
}
// superclass method
Shape.prototype.move = function (x, y) {
this.x += x;
this.y += y;
console.info("Shape moved.");
};
// Rectangle - subclass
function Rectangle() {
Shape.call(this); // call super constructor.
}
// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype, {
// If you don't set Rectangle.prototype.constructor to Rectangle,
// it will take the prototype.constructor of Shape (parent).
// To avoid that, we set the prototype.constructor to Rectangle (child).
constructor: {
value: Rectangle,
enumerable: false,
writable: true,
configurable: true,
},
});
const rect = new Rectangle();
console.log("Is rect an instance of Rectangle?", rect instanceof Rectangle); // true
console.log("Is rect an instance of Shape?", rect instanceof Shape); // true
rect.move(1, 1); // Logs 'Shape moved.'
```
Note that there are caveats to watch out for using `create()`, such as re-adding the [`constructor`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) property to ensure proper semantics. Although `Object.create()` is believed to have better performance than mutating the prototype with {{jsxref("Object.setPrototypeOf()")}}, the difference is in fact negligible if no instances have been created and property accesses haven't been optimized yet. In modern code, the [class](/en-US/docs/Web/JavaScript/Reference/Classes) syntax should be preferred in any case.
### Using propertiesObject argument with Object.create()
`Object.create()` allows fine-tuned control over the object creation process. The [object initializer syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) is, in fact, a syntax sugar of `Object.create()`. With `Object.create()`, we can create objects with a designated prototype and also some properties. Note that the second parameter maps keys to _property descriptors_ — this means you can control each property's enumerability, configurability, etc. as well, which you can't do in object initializers.
```js
o = {};
// Is equivalent to:
o = Object.create(Object.prototype);
o = Object.create(Object.prototype, {
// foo is a regular data property
foo: {
writable: true,
configurable: true,
value: "hello",
},
// bar is an accessor property
bar: {
configurable: false,
get() {
return 10;
},
set(value) {
console.log("Setting `o.bar` to", value);
},
},
});
// Create a new object whose prototype is a new, empty
// object and add a single property 'p', with value 42.
o = Object.create({}, { p: { value: 42 } });
```
With `Object.create()`, we can create an object [with `null` as prototype](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects). The equivalent syntax in object initializers would be the [`__proto__`](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#prototype_setter) key.
```js
o = Object.create(null);
// Is equivalent to:
o = { __proto__: null };
```
By default properties are _not_ writable, enumerable or configurable.
```js
o.p = 24; // throws in strict mode
o.p; // 42
o.q = 12;
for (const prop in o) {
console.log(prop);
}
// 'q'
delete o.p;
// false; throws in strict mode
```
To specify a property with the same attributes as in an initializer, explicitly specify `writable`, `enumerable` and `configurable`.
```js
o2 = Object.create(
{},
{
p: {
value: 42,
writable: true,
enumerable: true,
configurable: true,
},
},
);
// This is not equivalent to:
// o2 = Object.create({ p: 42 })
// which will create an object with prototype { p: 42 }
```
You can use `Object.create()` to mimic the behavior of the [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) operator.
```js
function Constructor() {}
o = new Constructor();
// Is equivalent to:
o = Object.create(Constructor.prototype);
```
Of course, if there is actual initialization code in the `Constructor` function, the `Object.create()` method cannot reflect it.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.create` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- {{jsxref("Object.defineProperty()")}}
- {{jsxref("Object.defineProperties()")}}
- {{jsxref("Object.prototype.isPrototypeOf()")}}
- {{jsxref("Reflect.construct()")}}
- [Object.getPrototypeOf](https://johnresig.com/blog/objectgetprototypeof/) by John Resig (2008)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/setprototypeof/index.md | ---
title: Object.setPrototypeOf()
slug: Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.setPrototypeOf
---
{{JSRef}}
The **`Object.setPrototypeOf()`** static method sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null).
> **Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `Object.setPrototypeOf(...)` statement, but may extend to **_any_** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in [JavaScript engine fundamentals: optimizing prototypes](https://mathiasbynens.be/notes/prototypes).
>
> Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the `[[Prototype]]` of an object. Instead, create a new object with the desired `[[Prototype]]` using {{jsxref("Object.create()")}}.
{{EmbedInteractiveExample("pages/js/object-setprototypeof.html")}}
## Syntax
```js-nolint
Object.setPrototypeOf(obj, prototype)
```
### Parameters
- `obj`
- : The object which is to have its prototype set.
- `prototype`
- : The object's new prototype (an object or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null)).
### Return value
The specified object.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown in one of the following cases:
- The `obj` parameter is `undefined` or `null`.
- The `obj` parameter is [non-extensible](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible), or it's an [immutable prototype exotic object](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-immutable-prototype-exotic-objects), such as `Object.prototype` or [`window`](/en-US/docs/Web/API/Window). However, the error is not thrown if the new prototype is the same value as the original prototype of `obj`.
- The `prototype` parameter is not an object or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null).
## Description
`Object.setPrototypeOf()` is generally considered the proper way to set the prototype of an object. You should always use it in favor of the deprecated [`Object.prototype.__proto__`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto) accessor.
If the `obj` parameter is not an object (e.g. number, string, etc.), this method does nothing — without coercing it to an object or attempting to set its prototype — and directly returns `obj` as a primitive value. If `prototype` is the same value as the prototype of `obj`, then `obj` is directly returned, without causing a `TypeError` even when `obj` has immutable prototype.
For security concerns, there are certain built-in objects that are designed to have an _immutable prototype_. This prevents prototype pollution attacks, especially [proxy-related ones](https://github.com/tc39/ecma262/issues/272). The core language only specifies `Object.prototype` as an immutable prototype exotic object, whose prototype is always `null`. In browsers, [`window`](/en-US/docs/Web/API/Window) and [`location`](/en-US/docs/Web/API/Window/location) are two other very common examples.
```js
Object.isExtensible(Object.prototype); // true; you can add more properties
Object.setPrototypeOf(Object.prototype, {}); // TypeError: Immutable prototype object '#<Object>' cannot have their prototype set
Object.setPrototypeOf(Object.prototype, null); // No error; the prototype of `Object.prototype` is already `null`
```
## Examples
### Pseudoclassical inheritance using Object.setPrototypeOf()
Inheritance in JS using classes.
```js
class Human {}
class SuperHero extends Human {}
const superMan = new SuperHero();
```
However, if we want to implement subclasses without using `class`, we can do the following:
```js
function Human(name, level) {
this.name = name;
this.level = level;
}
function SuperHero(name, level) {
Human.call(this, name, level);
}
Object.setPrototypeOf(SuperHero.prototype, Human.prototype);
// Set the `[[Prototype]]` of `SuperHero.prototype`
// to `Human.prototype`
// To set the prototypal inheritance chain
Human.prototype.speak = function () {
return `${this.name} says hello.`;
};
SuperHero.prototype.fly = function () {
return `${this.name} is flying.`;
};
const superMan = new SuperHero("Clark Kent", 1);
console.log(superMan.fly());
console.log(superMan.speak());
```
The similarity between classical inheritance (with classes) and pseudoclassical inheritance (with constructors' `prototype` property) as done above is mentioned in [Inheritance chains](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#building_longer_inheritance_chains).
Since function constructors' [`prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype) property is writable, you can reassign it to a new object created with [`Object.create()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#classical_inheritance_with_object.create) to achieve the same inheritance chain as well. There are caveats to watch out when using `create()`, such as remembering to re-add the [`constructor`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) property.
In the example below, which also uses classes, `SuperHero` is made to inherit from `Human` without using `extends` by using `setPrototypeOf()` instead.
> **Warning:** It is not advisable to use `setPrototypeOf()` instead of `extends` due to performance and readability reasons.
```js
class Human {}
class SuperHero {}
// Set the instance properties
Object.setPrototypeOf(SuperHero.prototype, Human.prototype);
// Hook up the static properties
Object.setPrototypeOf(SuperHero, Human);
const superMan = new SuperHero();
```
Subclassing without `extends` is mentioned in [ES-6 subclassing](https://hacks.mozilla.org/2015/08/es6-in-depth-subclassing/).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.setPrototypeOf` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- {{jsxref("Reflect.setPrototypeOf()")}}
- {{jsxref("Object.prototype.isPrototypeOf()")}}
- {{jsxref("Object.getPrototypeOf()")}}
- [`Object.prototype.__proto__`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto)
- [Inheritance chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#building_longer_inheritance_chains)
- [ES6 In Depth: Subclassing](https://hacks.mozilla.org/2015/08/es6-in-depth-subclassing/) on hacks.mozilla.org (2015)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/fromentries/index.md | ---
title: Object.fromEntries()
slug: Web/JavaScript/Reference/Global_Objects/Object/fromEntries
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.fromEntries
---
{{JSRef}}
The **`Object.fromEntries()`** static method transforms a list of key-value pairs into an object.
{{EmbedInteractiveExample("pages/js/object-fromentries.html")}}
## Syntax
```js-nolint
Object.fromEntries(iterable)
```
### Parameters
- `iterable`
- : An [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), such as an {{jsxref("Array")}} or {{jsxref("Map")}}, containing a list of objects. Each object should have two properties:
- `0`
- : A string or [symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) representing the property key.
- `1`
- : The property value.
Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value.
### Return value
A new object whose properties are given by the entries of the iterable.
## Description
The `Object.fromEntries()` method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The `iterable` argument is expected to be an object that implements an `@@iterator` method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key.
`Object.fromEntries()` performs the reverse of {{jsxref("Object.entries()")}}, except that `Object.entries()` only returns string-keyed properties, while `Object.fromEntries()` can also create symbol-keyed properties.
> **Note:** Unlike {{jsxref("Array.from()")}}, `Object.fromEntries()` does not use the value of `this`, so calling it on another constructor does not create objects of that type.
## Examples
### Converting a Map to an Object
With `Object.fromEntries`, you can convert from {{jsxref("Map")}} to {{jsxref("Object")}}:
```js
const map = new Map([
["foo", "bar"],
["baz", 42],
]);
const obj = Object.fromEntries(map);
console.log(obj); // { foo: "bar", baz: 42 }
```
### Converting an Array to an Object
With `Object.fromEntries`, you can convert from {{jsxref("Array")}} to {{jsxref("Object")}}:
```js
const arr = [
["0", "a"],
["1", "b"],
["2", "c"],
];
const obj = Object.fromEntries(arr);
console.log(obj); // { 0: "a", 1: "b", 2: "c" }
```
### Object transformations
With `Object.fromEntries`, its reverse method {{jsxref("Object.entries()")}}, and [array manipulation methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#instance_methods), you are able to transform objects like this:
```js
const object1 = { a: 1, b: 2, c: 3 };
const object2 = Object.fromEntries(
Object.entries(object1).map(([key, val]) => [key, val * 2]),
);
console.log(object2);
// { a: 2, b: 4, c: 6 }
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.fromEntries` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- {{jsxref("Object.entries()")}}
- {{jsxref("Object.keys()")}}
- {{jsxref("Object.values()")}}
- {{jsxref("Object.prototype.propertyIsEnumerable()")}}
- {{jsxref("Object.create()")}}
- {{jsxref("Map.prototype.entries()")}}
- {{jsxref("Map.prototype.keys()")}}
- {{jsxref("Map.prototype.values()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/hasownproperty/index.md | ---
title: Object.prototype.hasOwnProperty()
slug: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
page-type: javascript-instance-method
browser-compat: javascript.builtins.Object.hasOwnProperty
---
{{JSRef}}
The **`hasOwnProperty()`** method of {{jsxref("Object")}} instances returns a boolean indicating whether this
object has the specified property as its own property (as opposed to inheriting
it).
> **Note:** {{jsxref("Object.hasOwn()")}} is recommended over
> `hasOwnProperty()`, in browsers where it is supported.
{{EmbedInteractiveExample("pages/js/object-prototype-hasownproperty.html")}}
## Syntax
```js-nolint
hasOwnProperty(prop)
```
### Parameters
- `prop`
- : The {{jsxref("String")}} name or [Symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) of the property to test.
### Return value
Returns `true` if the object has the specified property as own property; `false`
otherwise.
## Description
The **`hasOwnProperty()`** method returns `true` if the specified property is a
direct property of the object — even if the value is `null` or `undefined`. The
method returns `false` if the property is inherited, or has not been declared at
all. Unlike the {{jsxref("Operators/in", "in")}} operator, this
method does not check for the specified property in the object's prototype
chain.
The method can be called on _most_ JavaScript objects, because most objects
descend from {{jsxref("Object")}}, and hence inherit its methods. For
example {{jsxref("Array")}} is an {{jsxref("Object")}}, so you can
use `hasOwnProperty()` method to check whether an index exists:
```js
const fruits = ["Apple", "Banana", "Watermelon", "Orange"];
fruits.hasOwnProperty(3); // true ('Orange')
fruits.hasOwnProperty(4); // false - not defined
```
The method will not be available in objects where it is reimplemented, or on
[`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) (as these don't inherit from
`Object.prototype`). Examples for these cases are given below.
## Examples
### Using hasOwnProperty to test for an own property's existence
The following code shows how to determine whether the `example` object contains a property named `prop`.
```js
const example = {};
example.hasOwnProperty("prop"); // false
example.prop = "exists";
example.hasOwnProperty("prop"); // true - 'prop' has been defined
example.prop = null;
example.hasOwnProperty("prop"); // true - own property exists with value of null
example.prop = undefined;
example.hasOwnProperty("prop"); // true - own property exists with value of undefined
```
### Direct vs. inherited properties
The following example differentiates between direct properties and properties inherited through the prototype chain:
```js
const example = {};
example.prop = "exists";
// `hasOwnProperty` will only return true for direct properties:
example.hasOwnProperty("prop"); // true
example.hasOwnProperty("toString"); // false
example.hasOwnProperty("hasOwnProperty"); // false
// The `in` operator will return true for direct or inherited properties:
"prop" in example; // true
"toString" in example; // true
"hasOwnProperty" in example; // true
```
### Iterating over the properties of an object
The following example shows how to iterate over the enumerable properties of an
object without executing on inherited properties.
```js
const buz = {
fog: "stack",
};
for (const name in buz) {
if (buz.hasOwnProperty(name)) {
console.log(`this is fog (${name}) for sure. Value: ${buz[name]}`);
} else {
console.log(name); // toString or something else
}
}
```
Note that the {{jsxref("Statements/for...in", "for...in")}} loop
only iterates enumerable items: the absence of non-enumerable properties emitted
from the loop does not imply that `hasOwnProperty` itself is confined strictly
to enumerable items. You can iterate over non-enumerable properties with
{{jsxref("Object.getOwnPropertyNames()")}}.
### Using hasOwnProperty as a property name
JavaScript does not protect the property name `hasOwnProperty`; an object that
has a property with this name may return incorrect results:
```js
const foo = {
hasOwnProperty() {
return false;
},
bar: "Here be dragons",
};
foo.hasOwnProperty("bar"); // re-implementation always returns false
```
The recommended way to overcome this problem is to instead use
{{jsxref("Object.hasOwn()")}} (in browsers that support it). Other
alternatives include using an _external_ `hasOwnProperty`:
```js
const foo = { bar: "Here be dragons" };
// Use Object.hasOwn() method - recommended
Object.hasOwn(foo, "bar"); // true
// Use the hasOwnProperty property from the Object prototype
Object.prototype.hasOwnProperty.call(foo, "bar"); // true
// Use another Object's hasOwnProperty
// and call it with 'this' set to foo
({}).hasOwnProperty.call(foo, "bar"); // true
```
Note that in the first two cases there are no newly created objects.
### Objects created with Object.create(null)
[`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) do not
inherit from `Object.prototype`, making `hasOwnProperty()` inaccessible.
```js
const foo = Object.create(null);
foo.prop = "exists";
foo.hasOwnProperty("prop"); // Uncaught TypeError: foo.hasOwnProperty is not a function
```
The solutions in this case are the same as for the previous section: use
{{jsxref("Object.hasOwn()")}} by preference, otherwise use an
external object's `hasOwnProperty()`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Object.hasOwn()")}}
- [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
- {{jsxref("Object.getOwnPropertyNames()")}}
- {{jsxref("Statements/for...in", "for...in")}}
- {{jsxref("Operators/in", "in")}}
- [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/getownpropertysymbols/index.md | ---
title: Object.getOwnPropertySymbols()
slug: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.getOwnPropertySymbols
---
{{JSRef}}
The **`Object.getOwnPropertySymbols()`** static method returns an array of all symbol properties found directly upon a given object.
{{EmbedInteractiveExample("pages/js/object-getownpropertysymbols.html")}}
## Syntax
```js-nolint
Object.getOwnPropertySymbols(obj)
```
### Parameters
- `obj`
- : The object whose symbol properties are to be returned.
### Return value
An array of all symbol properties found directly upon the given object.
## Description
Similar to {{jsxref("Object.getOwnPropertyNames()")}}, you can get all symbol properties of a given object as an array of symbols. Note that {{jsxref("Object.getOwnPropertyNames()")}} itself does not contain the symbol properties of an object and only the string properties.
As all objects have no own symbol properties initially, `Object.getOwnPropertySymbols()` returns an empty array unless you have set symbol properties on your object.
## Examples
### Using Object.getOwnPropertySymbols()
```js
const obj = {};
const a = Symbol("a");
const b = Symbol.for("b");
obj[a] = "localSymbol";
obj[b] = "globalSymbol";
const objectSymbols = Object.getOwnPropertySymbols(obj);
console.log(objectSymbols.length); // 2
console.log(objectSymbols); // [Symbol(a), Symbol(b)]
console.log(objectSymbols[0]); // Symbol(a)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.getOwnPropertySymbols` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol)
- {{jsxref("Object.getOwnPropertyNames()")}}
- {{jsxref("Symbol")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/isprototypeof/index.md | ---
title: Object.prototype.isPrototypeOf()
slug: Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf
page-type: javascript-instance-method
browser-compat: javascript.builtins.Object.isPrototypeOf
---
{{JSRef}}
The **`isPrototypeOf()`** method of {{jsxref("Object")}} instances checks if this object exists in another object's prototype chain.
> **Note:** `isPrototypeOf()` differs from the [`instanceof`](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) operator. In the expression `object instanceof AFunction`, `object`'s prototype chain is checked against `AFunction.prototype`, not against `AFunction` itself.
{{EmbedInteractiveExample("pages/js/object-prototype-isprototypeof.html")}}
## Syntax
```js-nolint
isPrototypeOf(object)
```
### Parameters
- `object`
- : The object whose prototype chain will be searched.
### Return value
A boolean indicating whether the calling object (`this`) lies in the prototype chain of `object`. Directly returns `false` when `object` is not an object (i.e. a primitive).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `this` is `null` or `undefined` (because it can't be [converted to an object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion)).
## Description
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `isPrototypeOf()` method. This method allows you to check whether or not the object exists within another object's prototype chain. If the `object` passed as the parameter is not an object (i.e. a primitive), the method directly returns `false`. Otherwise, the `this` value is [converted to an object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion), and the prototype chain of `object` is searched for the `this` value, until the end of the chain is reached or the `this` value is found.
## Examples
### Using isPrototypeOf()
This example demonstrates that `Baz.prototype`, `Bar.prototype`, `Foo.prototype` and `Object.prototype` exist in the prototype chain for object `baz`:
```js
class Foo {}
class Bar extends Foo {}
class Baz extends Bar {}
const foo = new Foo();
const bar = new Bar();
const baz = new Baz();
// prototype chains:
// foo: Foo --> Object
// bar: Bar --> Foo --> Object
// baz: Baz --> Bar --> Foo --> Object
console.log(Baz.prototype.isPrototypeOf(baz)); // true
console.log(Baz.prototype.isPrototypeOf(bar)); // false
console.log(Baz.prototype.isPrototypeOf(foo)); // false
console.log(Bar.prototype.isPrototypeOf(baz)); // true
console.log(Bar.prototype.isPrototypeOf(foo)); // false
console.log(Foo.prototype.isPrototypeOf(baz)); // true
console.log(Foo.prototype.isPrototypeOf(bar)); // true
console.log(Object.prototype.isPrototypeOf(baz)); // true
```
The `isPrototypeOf()` method — along with the {{jsxref("Operators/instanceof", "instanceof")}} operator — comes in particularly handy if you have code that can only function when dealing with objects descended from a specific prototype chain; e.g., to guarantee that certain methods or properties will be present on that object.
For example, to execute some code that's only safe to run if a `baz` object has `Foo.prototype` in its prototype chain, you can do this:
```js
if (Foo.prototype.isPrototypeOf(baz)) {
// do something safe
}
```
However, `Foo.prototype` existing in `baz`'s prototype chain doesn't imply `baz` was created using `Foo` as its constructor. For example, `baz` could be directly assigned with `Foo.prototype` as its prototype. In this case, if your code reads [private fields](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) of `Foo` from `baz`, it would still fail:
```js
class Foo {
#value = "foo";
static getValue(x) {
return x.#value;
}
}
const baz = { __proto__: Foo.prototype };
if (Foo.prototype.isPrototypeOf(baz)) {
console.log(Foo.getValue(baz)); // TypeError: Cannot read private member #value from an object whose class did not declare it
}
```
The same applies to [`instanceof`](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof). If you need to read private fields in a secure way, offer a branded check method using [`in`](/en-US/docs/Web/JavaScript/Reference/Operators/in) instead.
```js
class Foo {
#value = "foo";
static getValue(x) {
return x.#value;
}
static isFoo(x) {
return #value in x;
}
}
const baz = { __proto__: Foo.prototype };
if (Foo.isFoo(baz)) {
// Doesn't run, because baz is not a Foo
console.log(Foo.getValue(baz));
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Operators/instanceof", "instanceof")}}
- {{jsxref("Object.getPrototypeOf()")}}
- {{jsxref("Object.setPrototypeOf()")}}
- [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/defineproperties/index.md | ---
title: Object.defineProperties()
slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperties
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.defineProperties
---
{{JSRef}}
The **`Object.defineProperties()`** static method defines new or
modifies existing properties directly on an object, returning the object.
{{EmbedInteractiveExample("pages/js/object-defineproperties.html")}}
## Syntax
```js-nolint
Object.defineProperties(obj, props)
```
### Parameters
- `obj`
- : The object on which to define or modify properties.
- `props`
- : An object whose keys represent the names of properties to be defined or modified and
whose values are objects describing those properties. Each value in `props`
must be either a data descriptor or an accessor descriptor; it cannot be both (see
{{jsxref("Object.defineProperty()")}} for more details).
Data descriptors and accessor descriptors may optionally contain the following keys:
- `configurable`
- : `true` if and only if the type of this property descriptor may be
changed and if the property may be deleted from the corresponding object.
**Defaults to `false`.**
- `enumerable`
- : `true` if and only if this property shows up during enumeration of
the properties on the corresponding object.
**Defaults to `false`.**
A data descriptor also has the following optional keys:
- `value`
- : The value associated with the property. Can be any valid JavaScript value
(number, object, function, etc.).
**Defaults to {{jsxref("undefined")}}.**
- `writable`
- : `true` if and only if the value associated with the property may be
changed with an {{jsxref("Operators", "assignment operator", "assignment_operators", 1)}}.
**Defaults to `false`.**
An accessor descriptor also has the following optional keys:
- `get`
- : A function which serves as a getter for the property, or {{jsxref("undefined")}}
if there is no getter. The function's return value will be used as the value of
the property.
**Defaults to {{jsxref("undefined")}}.**
- `set`
- : A function which serves as a setter for the property, or {{jsxref("undefined")}}
if there is no setter. The function will receive as its only argument the new
value being assigned to the property.
**Defaults to {{jsxref("undefined")}}.**
If a descriptor has neither of `value`, `writable`,
`get` and `set` keys, it is treated as a data descriptor. If a
descriptor has both `value` or `writable` and `get`
or `set` keys, an exception is thrown.
### Return value
The object that was passed to the function.
## Examples
### Using Object.defineProperties
```js
const obj = {};
Object.defineProperties(obj, {
property1: {
value: true,
writable: true,
},
property2: {
value: "Hello",
writable: false,
},
// etc. etc.
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.defineProperties` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- {{jsxref("Object.defineProperty()")}}
- {{jsxref("Object.keys()")}}
- [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/keys/index.md | ---
title: Object.keys()
slug: Web/JavaScript/Reference/Global_Objects/Object/keys
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.keys
---
{{JSRef}}
The **`Object.keys()`** static method returns an array of a given object's own enumerable string-keyed property names.
{{EmbedInteractiveExample("pages/js/object-keys.html")}}
## Syntax
```js-nolint
Object.keys(obj)
```
### Parameters
- `obj`
- : An object.
### Return value
An array of strings representing the given object's own enumerable string-keyed property keys.
## Description
`Object.keys()` returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon `object`. This is the same as iterating with a {{jsxref("Statements/for...in", "for...in")}} loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.keys()` is the same as that provided by a {{jsxref("Statements/for...in", "for...in")}} loop.
If you need the property values, use {{jsxref("Object.values()")}} instead. If you need both the property keys and values, use {{jsxref("Object.entries()")}} instead.
## Examples
### Using Object.keys()
```js
// Simple array
const arr = ["a", "b", "c"];
console.log(Object.keys(arr)); // ['0', '1', '2']
// Array-like object
const obj = { 0: "a", 1: "b", 2: "c" };
console.log(Object.keys(obj)); // ['0', '1', '2']
// Array-like object with random key ordering
const anObj = { 100: "a", 2: "b", 7: "c" };
console.log(Object.keys(anObj)); // ['2', '7', '100']
// getFoo is a non-enumerable property
const myObj = Object.create(
{},
{
getFoo: {
value() {
return this.foo;
},
},
},
);
myObj.foo = 1;
console.log(Object.keys(myObj)); // ['foo']
```
If you want _all_ string-keyed own properties, including non-enumerable ones, see {{jsxref("Object.getOwnPropertyNames()")}}.
### Using Object.keys() on primitives
Non-object arguments are [coerced to objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion). [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) and [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) cannot be coerced to objects and throw a {{jsxref("TypeError")}} upfront. Only strings may have own enumerable properties, while all other primitives return an empty array.
```js
// Strings have indices as enumerable own properties
console.log(Object.keys("foo")); // ['0', '1', '2']
// Other primitives except undefined and null have no own properties
console.log(Object.keys(100)); // []
```
> **Note:** In ES5, passing a non-object to `Object.keys()` threw a {{jsxref("TypeError")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.keys` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
- {{jsxref("Object.entries()")}}
- {{jsxref("Object.values()")}}
- {{jsxref("Object.prototype.propertyIsEnumerable()")}}
- {{jsxref("Object.create()")}}
- {{jsxref("Object.getOwnPropertyNames()")}}
- {{jsxref("Map.prototype.keys()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/__definesetter__/index.md | ---
title: Object.prototype.__defineSetter__()
slug: Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.Object.defineSetter
---
{{JSRef}}{{Deprecated_Header}}
> **Note:** This feature is deprecated in favor of defining [setters](/en-US/docs/Web/JavaScript/Reference/Functions/set) using the [object initializer syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) or the {{jsxref("Object.defineProperty()")}} API. This method's behavior is only specified for web compatibility, and is not required to be implemented in any platform. It may not work everywhere.
The **`__defineSetter__()`** method of {{jsxref("Object")}} instances binds an object's property to a function to be called when an attempt is made to set that property.
## Syntax
```js-nolint
__defineSetter__(prop, func)
```
### Parameters
- `prop`
- : A string containing the name of the property that the setter `func` is bound to.
- `func`
- : A function to be called when there is an attempt to set the specified property. This function receives the following parameter:
- `val`
- : The value attempted to be assigned to `prop`.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `func` is not a function.
## Description
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `__defineSetter__()` method. This method allows a [setter](/en-US/docs/Web/JavaScript/Reference/Functions/set) to be defined on a pre-existing object. This is equivalent to [`Object.defineProperty(obj, prop, { set: func, configurable: true, enumerable: true })`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty), which means the property is enumerable and configurable, and any existing getter, if present, is preserved.
`__defineSetter__()` is defined in the spec as "normative optional", which means no implementation is required to implement this. However, all major browsers implement it, and due to its continued usage, it's unlikely to be removed. If a browser implements `__defineSetter__()`, it also needs to implement the [`__lookupGetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__), [`__lookupSetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__), and [`__defineGetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__) methods.
## Examples
### Using \_\_defineSetter\_\_()
```js
const o = {};
o.__defineSetter__("value", function (val) {
this.anotherValue = val;
});
o.value = 5;
console.log(o.value); // undefined
console.log(o.anotherValue); // 5
```
### Defining a setter property in standard ways
You can use the `set` syntax to define a setter when the object is first initialized.
```js
const o = {
set value(val) {
this.anotherValue = val;
},
};
o.value = 5;
console.log(o.value); // undefined
console.log(o.anotherValue); // 5
```
You may also use {{jsxref("Object.defineProperty()")}} to define a setter on an object after it's been created. Compared to `__defineSetter__()`, this method allows you to control the setter's enumerability and configurability, as well as defining [symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) properties. The `Object.defineProperty()` method also works with [`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), which don't inherit from `Object.prototype` and therefore don't have the `__defineSetter__()` method.
```js
const o = {};
Object.defineProperty(o, "value", {
set(val) {
this.anotherValue = val;
},
configurable: true,
enumerable: true,
});
o.value = 5;
console.log(o.value); // undefined
console.log(o.anotherValue); // 5
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.prototype.__defineSetter__` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- [`Object.prototype.__defineGetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__)
- {{jsxref("Functions/set", "set")}}
- {{jsxref("Object.defineProperty()")}}
- [`Object.prototype.__lookupGetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__)
- [`Object.prototype.__lookupSetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__)
- [JS Guide: Defining Getters and Setters](/en-US/docs/Web/JavaScript/Guide/Working_with_objects#defining_getters_and_setters)
- [Firefox bug 647423](https://bugzil.la/647423)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/getownpropertydescriptors/index.md | ---
title: Object.getOwnPropertyDescriptors()
slug: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptors
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.getOwnPropertyDescriptors
---
{{JSRef}}
The **`Object.getOwnPropertyDescriptors()`** static method returns all
own property descriptors of a given object.
{{EmbedInteractiveExample("pages/js/object-getownpropertydescriptors.html")}}
## Syntax
```js-nolint
Object.getOwnPropertyDescriptors(obj)
```
### Parameters
- `obj`
- : The object for which to get all own property descriptors.
### Return value
An object containing all own property descriptors of an object. Might be an empty
object, if there are no properties.
## Description
This method permits examination of the precise description of all own properties of an
object. A _property_ in JavaScript consists of either a string-valued name or a
{{jsxref("Symbol")}} and a property descriptor. Further information about property
descriptor types and their attributes can be found in
{{jsxref("Object.defineProperty()")}}.
A _property descriptor_ is a record with some of the following attributes:
- `value`
- : The value associated with the property (data descriptors only).
- `writable`
- : `true` if and only if the value associated with the property may be
changed (data descriptors only).
- `get`
- : A function which serves as a getter for the property, or {{jsxref("undefined")}} if
there is no getter (accessor descriptors only).
- `set`
- : A function which serves as a setter for the property, or {{jsxref("undefined")}} if
there is no setter (accessor descriptors only).
- `configurable`
- : `true` if and only if the type of this property descriptor may be changed
and if the property may be deleted from the corresponding object.
- `enumerable`
- : `true` if and only if this property shows up during enumeration of the
properties on the corresponding object.
## Examples
### Creating a shallow copy
Whereas the {{jsxref("Object.assign()")}} method will only copy enumerable and own
properties from a source object to a target object, you are able to use this method and
{{jsxref("Object.create()")}} for a [shallow copy](/en-US/docs/Glossary/Shallow_copy) between two unknown objects:
```js
Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj),
);
```
### Creating a subclass
A typical way of creating a subclass is to define the subclass, set its prototype to an
instance of the superclass, and then define properties on that instance. This can get
awkward especially for getters and setters. Instead, you can use this code to set the
prototype:
```js
function superclass() {}
superclass.prototype = {
// Define the superclass constructor, methods, and properties here
};
function subclass() {}
subclass.prototype = Object.create(superclass.prototype, {
// Define the subclass constructor, methods, and properties here
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.getOwnPropertyDescriptors` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- {{jsxref("Object.getOwnPropertyDescriptor()")}}
- {{jsxref("Object.defineProperty()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/hasown/index.md | ---
title: Object.hasOwn()
slug: Web/JavaScript/Reference/Global_Objects/Object/hasOwn
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.hasOwn
---
{{JSRef}}
The **`Object.hasOwn()`** static method returns `true` if the specified object has the indicated property as its _own_ property.
If the property is inherited, or does not exist, the method returns `false`.
> **Note:** `Object.hasOwn()` is intended as a replacement for {{jsxref("Object.prototype.hasOwnProperty()")}}.
{{EmbedInteractiveExample("pages/js/object-hasown.html")}}
## Syntax
```js-nolint
Object.hasOwn(obj, prop)
```
### Parameters
- `obj`
- : The JavaScript object instance to test.
- `prop`
- : The {{jsxref("String")}} name or [Symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) of the property to test.
### Return value
`true` if the specified object has directly defined the specified property.
Otherwise `false`
## Description
The **`Object.hasOwn()`** method returns `true` if the specified property is a
direct property of the object — even if the property value is `null` or `undefined`.
The method returns `false` if the property is inherited, or has not been declared at all.
Unlike the {{jsxref("Operators/in", "in")}} operator, this
method does not check for the specified property in the object's prototype chain.
It is recommended over {{jsxref("Object.prototype.hasOwnProperty()")}} because
it works for [`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) and with objects that
have overridden the inherited `hasOwnProperty()` method. While it is possible to
workaround these problems by calling `Object.prototype.hasOwnProperty()` on an
external object, `Object.hasOwn()` is more intuitive.
## Examples
### Using hasOwn to test for a property's existence
The following code shows how to determine whether the `example` object contains a property named `prop`.
```js
const example = {};
Object.hasOwn(example, "prop"); // false - 'prop' has not been defined
example.prop = "exists";
Object.hasOwn(example, "prop"); // true - 'prop' has been defined
example.prop = null;
Object.hasOwn(example, "prop"); // true - own property exists with value of null
example.prop = undefined;
Object.hasOwn(example, "prop"); // true - own property exists with value of undefined
```
### Direct vs. inherited properties
The following example differentiates between direct properties and properties inherited through the prototype chain:
```js
const example = {};
example.prop = "exists";
// `hasOwn` will only return true for direct properties:
Object.hasOwn(example, "prop"); // true
Object.hasOwn(example, "toString"); // false
Object.hasOwn(example, "hasOwnProperty"); // false
// The `in` operator will return true for direct or inherited properties:
"prop" in example; // true
"toString" in example; // true
"hasOwnProperty" in example; // true
```
### Iterating over the properties of an object
To iterate over the enumerable properties of an object, you _should_ use:
```js
const example = { foo: true, bar: true };
for (const name of Object.keys(example)) {
// …
}
```
But if you need to use `for...in`, you can use `Object.hasOwn()` to skip the inherited properties:
```js
const example = { foo: true, bar: true };
for (const name in example) {
if (Object.hasOwn(example, name)) {
// …
}
}
```
### Checking if an Array index exists
The elements of an {{jsxref("Array")}} are defined as direct properties, so
you can use `hasOwn()` method to check whether a particular index exists:
```js
const fruits = ["Apple", "Banana", "Watermelon", "Orange"];
Object.hasOwn(fruits, 3); // true ('Orange')
Object.hasOwn(fruits, 4); // false - not defined
```
### Problematic cases for hasOwnProperty
This section demonstrates that `hasOwn()` is immune to the problems that affect
`hasOwnProperty`. Firstly, it can be used with objects that have reimplemented
`hasOwnProperty()`:
```js
const foo = {
hasOwnProperty() {
return false;
},
bar: "The dragons be out of office",
};
if (Object.hasOwn(foo, "bar")) {
console.log(foo.bar); // true - re-implementation of hasOwnProperty() does not affect Object
}
```
It can also be used with [`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects). These do
not inherit from `Object.prototype`, and so `hasOwnProperty()` is inaccessible.
```js
const foo = Object.create(null);
foo.prop = "exists";
if (Object.hasOwn(foo, "prop")) {
console.log(foo.prop); // true - works irrespective of how the object is created.
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.hasOwn` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- {{jsxref("Object.prototype.hasOwnProperty()")}}
- [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
- {{jsxref("Object.getOwnPropertyNames()")}}
- {{jsxref("Statements/for...in", "for...in")}}
- {{jsxref("Operators/in", "in")}}
- [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/proto/index.md | ---
title: Object.prototype.__proto__
slug: Web/JavaScript/Reference/Global_Objects/Object/proto
page-type: javascript-instance-accessor-property
status:
- deprecated
browser-compat: javascript.builtins.Object.proto
---
{{JSRef}}{{Deprecated_Header}}
> **Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `obj.__proto__ = ...` statement, but may extend to **_any_** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in [JavaScript engine fundamentals: optimizing prototypes](https://mathiasbynens.be/notes/prototypes).
> **Note:** The use of `__proto__` is controversial and discouraged. Its existence and exact behavior have only been standardized as a legacy feature to ensure web compatibility, while it presents several security issues and footguns. For better support, prefer {{jsxref("Object.getPrototypeOf()")}}/{{jsxref("Reflect.getPrototypeOf()")}} and {{jsxref("Object.setPrototypeOf()")}}/{{jsxref("Reflect.setPrototypeOf()")}} instead.
The **`__proto__`** accessor property of {{jsxref("Object")}} instances exposes the [`[[Prototype]]`](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) (either an object or {{jsxref("Operators/null", "null")}}) of this object.
The `__proto__` property can also be used in an object literal definition to set the object `[[Prototype]]` on creation, as an alternative to {{jsxref("Object.create()")}}. See: [object initializer / literal syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer). That syntax is standard and optimized for in implementations, and quite different from `Object.prototype.__proto__`.
## Syntax
```js-nolint
obj.__proto__
```
### Return value
If used as a getter, returns the object's `[[Prototype]]`.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if attempting to set the prototype of a [non-extensible](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible) object or an [immutable prototype exotic object](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-immutable-prototype-exotic-objects), such as `Object.prototype` or [`window`](/en-US/docs/Web/API/Window).
## Description
The `__proto__` getter function exposes the value of the internal `[[Prototype]]` of an object. For objects created using an object literal (unless you use the [prototype setter](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#prototype_setter) syntax), this value is `Object.prototype`. For objects created using array literals, this value is [`Array.prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). For functions, this value is {{jsxref("Function.prototype")}}. You can read more about the prototype chain in [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain).
The `__proto__` setter allows the `[[Prototype]]` of an object to be mutated. The value provided must be an object or {{jsxref("Operators/null", "null")}}. Providing any other value will do nothing.
Unlike {{jsxref("Object.getPrototypeOf()")}} and {{jsxref("Object.setPrototypeOf()")}}, which are always available on `Object` as static properties and always reflect the `[[Prototype]]` internal property, the `__proto__` property doesn't always exist as a property on all objects, and as a result doesn't reflect `[[Prototype]]` reliably.
The `__proto__` property is a simple accessor property on `Object.prototype` consisting of a getter and setter function. A property access for `__proto__` that eventually consults `Object.prototype` will find this property, but an access that does not consult `Object.prototype` will not. If some other `__proto__` property is found before `Object.prototype` is consulted, that property will hide the one found on `Object.prototype`.
[`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) don't inherit any property from `Object.prototype`, including the `__proto__` accessor property, so if you try to read `__proto__` on such an object, the value is always `undefined` regardless of the object's actual `[[Prototype]]`, and any assignment to `__proto__` would create a new property called `__proto__` instead of setting the object's prototype. Furthermore, `__proto__` can be redefined as an own property on any object instance through {{jsxref("Object.defineProperty()")}} without triggering the setter. In this case, `__proto__` will no longer be an accessor for `[[Prototype]]`. Therefore, always prefer {{jsxref("Object.getPrototypeOf()")}} and {{jsxref("Object.setPrototypeOf()")}} for setting and getting the `[[Prototype]]` of an object.
## Examples
### Using \_\_proto\_\_
```js
function Circle() {}
const shape = {};
const circle = new Circle();
// Set the object prototype.
// DEPRECATED. This is for example purposes only. DO NOT DO THIS in real code.
shape.__proto__ = circle;
// Get the object prototype
console.log(shape.__proto__ === Circle); // false
```
```js
const ShapeA = function () {};
const ShapeB = {
a() {
console.log("aaa");
},
};
ShapeA.prototype.__proto__ = ShapeB;
console.log(ShapeA.prototype.__proto__); // { a: [Function: a] }
const shapeA = new ShapeA();
shapeA.a(); // aaa
console.log(ShapeA.prototype === shapeA.__proto__); // true
```
```js
const ShapeC = function () {};
const ShapeD = {
a() {
console.log("a");
},
};
const shapeC = new ShapeC();
shapeC.__proto__ = ShapeD;
shapeC.a(); // a
console.log(ShapeC.prototype === shapeC.__proto__); // false
```
```js
function Test() {}
Test.prototype.myName = function () {
console.log("myName");
};
const test = new Test();
console.log(test.__proto__ === Test.prototype); // true
test.myName(); // myName
const obj = {};
obj.__proto__ = Test.prototype;
obj.myName(); // myName
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Object.prototype.isPrototypeOf()")}}
- {{jsxref("Object.getPrototypeOf()")}}
- {{jsxref("Object.setPrototypeOf()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/assign/index.md | ---
title: Object.assign()
slug: Web/JavaScript/Reference/Global_Objects/Object/assign
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.assign
---
{{JSRef}}
The **`Object.assign()`** static method
copies all {{jsxref("Object/propertyIsEnumerable", "enumerable", "", 1)}}
{{jsxref("Object/hasOwn", "own properties", "", 1)}} from one or more
_source objects_ to a _target object_. It returns the modified target
object.
{{EmbedInteractiveExample("pages/js/object-assign.html")}}
## Syntax
```js-nolint
Object.assign(target)
Object.assign(target, source1)
Object.assign(target, source1, source2)
Object.assign(target, source1, source2, /* …, */ sourceN)
```
### Parameters
- `target`
- : The target object — what to apply the sources' properties to, which is returned
after it is modified.
- `source1`, …, `sourceN`
- : The source object(s) — objects containing the properties you want to apply.
### Return value
The target object.
## Description
Properties in the target object are overwritten by properties in the sources if they
have the same {{jsxref("Object/keys", "key", "", 1)}}. Later sources' properties
overwrite earlier ones.
The `Object.assign()` method only copies _enumerable_ and
_own_ properties from a source object to a target object. It uses
`[[Get]]` on the source and `[[Set]]` on the target, so it will
invoke [getters](/en-US/docs/Web/JavaScript/Reference/Functions/get) and [setters](/en-US/docs/Web/JavaScript/Reference/Functions/set). Therefore it
_assigns_ properties, versus copying or defining new properties. This may make it
unsuitable for merging new properties into a prototype if the merge sources contain
getters.
For copying property definitions (including their enumerability) into prototypes, use
{{jsxref("Object.getOwnPropertyDescriptor()")}} and
{{jsxref("Object.defineProperty()")}} instead.
Both {{jsxref("String")}} and {{jsxref("Symbol")}} properties are copied.
In case of an error, for example if a property is non-writable, a
{{jsxref("TypeError")}} is raised, and the `target` object is
changed if any properties are added before the error is raised.
> **Note:** `Object.assign()` does not throw on
> [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) or {{jsxref("undefined")}} sources.
## Examples
### Cloning an object
```js
const obj = { a: 1 };
const copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
```
### Warning for Deep Clone
For [deep cloning](/en-US/docs/Glossary/Deep_copy), we need to use alternatives like [`structuredClone()`](/en-US/docs/Web/API/structuredClone), because `Object.assign()`
copies property values.
If the source value is a reference to an object, it only copies the reference value.
```js
const obj1 = { a: 0, b: { c: 0 } };
const obj2 = Object.assign({}, obj1);
console.log(obj2); // { a: 0, b: { c: 0 } }
obj1.a = 1;
console.log(obj1); // { a: 1, b: { c: 0 } }
console.log(obj2); // { a: 0, b: { c: 0 } }
obj2.a = 2;
console.log(obj1); // { a: 1, b: { c: 0 } }
console.log(obj2); // { a: 2, b: { c: 0 } }
obj2.b.c = 3;
console.log(obj1); // { a: 1, b: { c: 3 } }
console.log(obj2); // { a: 2, b: { c: 3 } }
// Deep Clone
const obj3 = { a: 0, b: { c: 0 } };
const obj4 = structuredClone(obj3);
obj3.a = 4;
obj3.b.c = 4;
console.log(obj4); // { a: 0, b: { c: 0 } }
```
### Merging objects
```js
const o1 = { a: 1 };
const o2 = { b: 2 };
const o3 = { c: 3 };
const obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
```
### Merging objects with same properties
```js
const o1 = { a: 1, b: 1, c: 1 };
const o2 = { b: 2, c: 2 };
const o3 = { c: 3 };
const obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
```
The properties are overwritten by other objects that have the same properties later in
the parameters order.
### Copying symbol-typed properties
```js
const o1 = { a: 1 };
const o2 = { [Symbol("foo")]: 2 };
const obj = Object.assign({}, o1, o2);
console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox)
Object.getOwnPropertySymbols(obj); // [Symbol(foo)]
```
### Properties on the prototype chain and non-enumerable properties cannot be copied
```js
const obj = Object.create(
// foo is on obj's prototype chain.
{ foo: 1 },
{
bar: {
value: 2, // bar is a non-enumerable property.
},
baz: {
value: 3,
enumerable: true, // baz is an own enumerable property.
},
},
);
const copy = Object.assign({}, obj);
console.log(copy); // { baz: 3 }
```
### Primitives will be wrapped to objects
```js
const v1 = "abc";
const v2 = true;
const v3 = 10;
const v4 = Symbol("foo");
const obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
// Primitives will be wrapped, null and undefined will be ignored.
// Note, only string wrappers can have own enumerable properties.
console.log(obj); // { "0": "a", "1": "b", "2": "c" }
```
### Exceptions will interrupt the ongoing copying task
```js
const target = Object.defineProperty({}, "foo", {
value: 1,
writable: false,
}); // target.foo is a read-only property
Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
// TypeError: "foo" is read-only
// The Exception is thrown when assigning target.foo
console.log(target.bar); // 2, the first source was copied successfully.
console.log(target.foo2); // 3, the first property of the second source was copied successfully.
console.log(target.foo); // 1, exception is thrown here.
console.log(target.foo3); // undefined, assign method has finished, foo3 will not be copied.
console.log(target.baz); // undefined, the third source will not be copied either.
```
### Copying accessors
```js
const obj = {
foo: 1,
get bar() {
return 2;
},
};
let copy = Object.assign({}, obj);
console.log(copy);
// { foo: 1, bar: 2 }
// The value of copy.bar is obj.bar's getter's return value.
// This is an assign function that copies full descriptors
function completeAssign(target, ...sources) {
sources.forEach((source) => {
const descriptors = Object.keys(source).reduce((descriptors, key) => {
descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
return descriptors;
}, {});
// By default, Object.assign copies enumerable Symbols, too
Object.getOwnPropertySymbols(source).forEach((sym) => {
const descriptor = Object.getOwnPropertyDescriptor(source, sym);
if (descriptor.enumerable) {
descriptors[sym] = descriptor;
}
});
Object.defineProperties(target, descriptors);
});
return target;
}
copy = completeAssign({}, obj);
console.log(copy);
// { foo:1, get bar() { return 2 } }
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.assign` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- {{jsxref("Object.defineProperties()")}}
- [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
- [Spread in object literals](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#spread_in_object_literals)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/is/index.md | ---
title: Object.is()
slug: Web/JavaScript/Reference/Global_Objects/Object/is
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.is
---
{{JSRef}}
The **`Object.is()`** static method determines whether two values are [the same value](/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is).
{{EmbedInteractiveExample("pages/js/object-is.html")}}
## Syntax
```js-nolint
Object.is(value1, value2)
```
### Parameters
- `value1`
- : The first value to compare.
- `value2`
- : The second value to compare.
### Return value
A boolean indicating whether or not the two arguments are the same value.
## Description
`Object.is()` determines whether two values are [the same value](/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). Two values are the same if one of the following holds:
- both {{jsxref("undefined")}}
- both [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null)
- both `true` or both `false`
- both strings of the same length with the same characters in the same order
- both the same object (meaning both values reference the same object in memory)
- both [BigInts](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) with the same numeric value
- both [symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) that reference the same symbol value
- both numbers and
- both `+0`
- both `-0`
- both {{jsxref("NaN")}}
- or both non-zero, not {{jsxref("NaN")}}, and have the same value
`Object.is()` is not equivalent to the [`==`](/en-US/docs/Web/JavaScript/Reference/Operators/Equality) operator. The `==` operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as `"" == false` being `true`), but `Object.is()` doesn't coerce either value.
`Object.is()` is also _not_ equivalent to the [`===`](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) operator. The only difference between `Object.is()` and `===` is in their treatment of signed zeros and `NaN` values. The `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal, but treats {{jsxref("NaN")}} as not equal to each other.
## Examples
### Using Object.is()
```js
// Case 1: Evaluation result is the same as using ===
Object.is(25, 25); // true
Object.is("foo", "foo"); // true
Object.is("foo", "bar"); // false
Object.is(null, null); // true
Object.is(undefined, undefined); // true
Object.is(window, window); // true
Object.is([], []); // false
const foo = { a: 1 };
const bar = { a: 1 };
const sameFoo = foo;
Object.is(foo, foo); // true
Object.is(foo, bar); // false
Object.is(foo, sameFoo); // true
// Case 2: Signed zero
Object.is(0, -0); // false
Object.is(+0, -0); // false
Object.is(-0, -0); // true
// Case 3: NaN
Object.is(NaN, 0 / 0); // true
Object.is(NaN, Number.NaN); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.is` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- [Equality comparisons and sameness](/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.md | ---
title: Object.getOwnPropertyDescriptor()
slug: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.getOwnPropertyDescriptor
---
{{JSRef}}
The **`Object.getOwnPropertyDescriptor()`** static method returns an
object describing the configuration of a specific property on a given object (that is,
one directly present on an object and not in the object's prototype chain). The object
returned is mutable but mutating it has no effect on the original property's
configuration.
{{EmbedInteractiveExample("pages/js/object-getownpropertydescriptor.html")}}
## Syntax
```js-nolint
Object.getOwnPropertyDescriptor(obj, prop)
```
### Parameters
- `obj`
- : The object in which to look for the property.
- `prop`
- : The name or {{jsxref("Symbol")}} of the property whose description is to be
retrieved.
### Return value
A property descriptor of the given property if it exists on the object,
{{jsxref("undefined")}} otherwise.
## Description
This method permits examination of the precise description of a property. A
_property_ in JavaScript consists of either a string-valued name or a
{{jsxref("Symbol")}} and a property descriptor. Further information about property
descriptor types and their attributes can be found in
{{jsxref("Object.defineProperty()")}}.
A _property descriptor_ is a record with some of the following attributes:
- `value`
- : The value associated with the property (data descriptors only).
- `writable`
- : `true` if and only if the value associated with the property may be
changed (data descriptors only).
- `get`
- : A function which serves as a getter for the property, or {{jsxref("undefined")}} if
there is no getter (accessor descriptors only).
- `set`
- : A function which serves as a setter for the property, or {{jsxref("undefined")}} if
there is no setter (accessor descriptors only).
- `configurable`
- : `true` if and only if the type of this property descriptor may be changed
and if the property may be deleted from the corresponding object.
- `enumerable`
- : `true` if and only if this property shows up during enumeration of the
properties on the corresponding object.
## Examples
### Using Object.getOwnPropertyDescriptor()
```js
let o, d;
o = {
get foo() {
return 17;
},
};
d = Object.getOwnPropertyDescriptor(o, "foo");
console.log(d);
// {
// configurable: true,
// enumerable: true,
// get: [Function: get foo],
// set: undefined
// }
o = { bar: 42 };
d = Object.getOwnPropertyDescriptor(o, "bar");
console.log(d);
// {
// configurable: true,
// enumerable: true,
// value: 42,
// writable: true
// }
o = { [Symbol.for("baz")]: 73 };
d = Object.getOwnPropertyDescriptor(o, Symbol.for("baz"));
console.log(d);
// {
// configurable: true,
// enumerable: true,
// value: 73,
// writable: true
// }
o = {};
Object.defineProperty(o, "qux", {
value: 8675309,
writable: false,
enumerable: false,
});
d = Object.getOwnPropertyDescriptor(o, "qux");
console.log(d);
// {
// value: 8675309,
// writable: false,
// enumerable: false,
// configurable: false
// }
```
### Non-object coercion
In ES5, if the first argument to this method is not an object (a primitive), then it
will cause a {{jsxref("TypeError")}}. In ES2015, a non-object first argument will be
coerced to an object at first.
```js
Object.getOwnPropertyDescriptor("foo", 0);
// TypeError: "foo" is not an object // ES5 code
Object.getOwnPropertyDescriptor("foo", 0);
// Object returned by ES2015 code: {
// configurable: false,
// enumerable: true,
// value: "f",
// writable: false
// }
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Object.defineProperty()")}}
- {{jsxref("Reflect.getOwnPropertyDescriptor()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/getprototypeof/index.md | ---
title: Object.getPrototypeOf()
slug: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.getPrototypeOf
---
{{JSRef}}
The **`Object.getPrototypeOf()`** static method returns the prototype
(i.e. the value of the internal `[[Prototype]]` property) of the specified
object.
{{EmbedInteractiveExample("pages/js/object-getprototypeof.html", "shorter")}}
## Syntax
```js-nolint
Object.getPrototypeOf(obj)
```
### Parameters
- `obj`
- : The object whose prototype is to be returned.
### Return value
The prototype of the given object, which may be [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null).
## Examples
### Using getPrototypeOf
```js
const proto = {};
const obj = Object.create(proto);
Object.getPrototypeOf(obj) === proto; // true
```
### Non-object coercion
In ES5, it will throw a {{jsxref("TypeError")}} exception if the `obj`
parameter isn't an object. In ES2015, the parameter will be coerced to an
{{jsxref("Object")}}.
```js
Object.getPrototypeOf("foo");
// TypeError: "foo" is not an object (ES5 code)
Object.getPrototypeOf("foo");
// String.prototype (ES2015 code)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.getPrototypeOf` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- {{jsxref("Object.prototype.isPrototypeOf()")}}
- {{jsxref("Object.setPrototypeOf()")}}
- [`Object.prototype.__proto__`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto)
- {{jsxref("Reflect.getPrototypeOf()")}}
- [Object.getPrototypeOf](https://johnresig.com/blog/objectgetprototypeof/) by John Resig (2008)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/values/index.md | ---
title: Object.values()
slug: Web/JavaScript/Reference/Global_Objects/Object/values
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.values
---
{{JSRef}}
The **`Object.values()`** static method returns an array of a given object's own enumerable string-keyed property values.
{{EmbedInteractiveExample("pages/js/object-values.html")}}
## Syntax
```js-nolint
Object.values(obj)
```
### Parameters
- `obj`
- : An object.
### Return value
An array containing the given object's own enumerable string-keyed property values.
## Description
`Object.values()` returns an array whose elements are values of enumerable string-keyed properties found directly upon `object`. This is the same as iterating with a {{jsxref("Statements/for...in", "for...in")}} loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.values()` is the same as that provided by a {{jsxref("Statements/for...in", "for...in")}} loop.
If you need the property keys, use {{jsxref("Object.keys()")}} instead. If you need both the property keys and values, use {{jsxref("Object.entries()")}} instead.
## Examples
### Using Object.values()
```js
const obj = { foo: "bar", baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]
// Array-like object
const arrayLikeObj1 = { 0: "a", 1: "b", 2: "c" };
console.log(Object.values(arrayLikeObj1)); // ['a', 'b', 'c']
// Array-like object with random key ordering
// When using numeric keys, the values are returned in the keys' numerical order
const arrayLikeObj2 = { 100: "a", 2: "b", 7: "c" };
console.log(Object.values(arrayLikeObj2)); // ['b', 'c', 'a']
// getFoo is a non-enumerable property
const myObj = Object.create(
{},
{
getFoo: {
value() {
return this.foo;
},
},
},
);
myObj.foo = "bar";
console.log(Object.values(myObj)); // ['bar']
```
### Using Object.values() on primitives
Non-object arguments are [coerced to objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion). [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) and [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) cannot be coerced to objects and throw a {{jsxref("TypeError")}} upfront. Only strings may have own enumerable properties, while all other primitives return an empty array.
```js
// Strings have indices as enumerable own properties
console.log(Object.values("foo")); // ['f', 'o', 'o']
// Other primitives except undefined and null have no own properties
console.log(Object.values(100)); // []
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.values` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
- {{jsxref("Object.keys()")}}
- {{jsxref("Object.entries()")}}
- {{jsxref("Object.prototype.propertyIsEnumerable()")}}
- {{jsxref("Object.create()")}}
- {{jsxref("Object.getOwnPropertyNames()")}}
- {{jsxref("Map.prototype.values()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/isextensible/index.md | ---
title: Object.isExtensible()
slug: Web/JavaScript/Reference/Global_Objects/Object/isExtensible
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.isExtensible
---
{{JSRef}}
The **`Object.isExtensible()`** static method determines if an object
is extensible (whether it can have new properties added to it).
{{EmbedInteractiveExample("pages/js/object-isextensible.html")}}
## Syntax
```js-nolint
Object.isExtensible(obj)
```
### Parameters
- `obj`
- : The object which should be checked.
### Return value
A {{jsxref("Boolean")}} indicating whether or not the given object is extensible.
## Description
Objects are extensible by default: they can have new properties added to them, and their `[[Prototype]]` can be re-assigned. An object can be marked as non-extensible using one of {{jsxref("Object.preventExtensions()")}}, {{jsxref("Object.seal()")}}, {{jsxref("Object.freeze()")}}, or {{jsxref("Reflect.preventExtensions()")}}.
## Examples
### Using Object.isExtensible
```js
// New objects are extensible.
const empty = {};
Object.isExtensible(empty); // true
// They can be made un-extensible
Object.preventExtensions(empty);
Object.isExtensible(empty); // false
// Sealed objects are by definition non-extensible.
const sealed = Object.seal({});
Object.isExtensible(sealed); // false
// Frozen objects are also by definition non-extensible.
const frozen = Object.freeze({});
Object.isExtensible(frozen); // false
```
### Non-object argument
In ES5, if the argument to this method is not an object (a primitive), then it will cause a {{jsxref("TypeError")}}. In ES2015, it will return `false` without any errors if a non-object argument is passed, since primitives are, by definition, immutable.
```js
Object.isExtensible(1);
// TypeError: 1 is not an object (ES5 code)
Object.isExtensible(1);
// false (ES2015 code)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Object.preventExtensions()")}}
- {{jsxref("Object.seal()")}}
- {{jsxref("Object.isSealed()")}}
- {{jsxref("Object.freeze()")}}
- {{jsxref("Object.isFrozen()")}}
- {{jsxref("Reflect.isExtensible()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/freeze/index.md | ---
title: Object.freeze()
slug: Web/JavaScript/Reference/Global_Objects/Object/freeze
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.freeze
---
{{JSRef}}
The **`Object.freeze()`** static method _freezes_ an object. Freezing an object [prevents extensions](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions) and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object's prototype cannot be re-assigned. `freeze()` returns the same object that was passed in.
Freezing an object is the highest integrity level that JavaScript provides.
{{EmbedInteractiveExample("pages/js/object-freeze.html")}}
## Syntax
```js-nolint
Object.freeze(obj)
```
### Parameters
- `obj`
- : The object to freeze.
### Return value
The object that was passed to the function.
## Description
Freezing an object is equivalent to [preventing extensions](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions) and then changing all existing [properties' descriptors'](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description) `configurable` to `false` — and for data properties, `writable` to `false` as well. Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a {{jsxref("TypeError")}} exception (most commonly, but not exclusively, when in {{jsxref("Strict_mode", "strict mode", "", 1)}}).
For data properties of a frozen object, their values cannot be changed since the `writable` and
`configurable` attributes are set to `false`. Accessor properties (getters and setters) work the same — the property value returned by the getter may still change, and the setter can still be called without throwing errors when setting the property. Note that values
that are objects can still be modified, unless they are also frozen. As an object, an
array can be frozen; after doing so, its elements cannot be altered and no elements can
be added to or removed from the array.
[Private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) do not have the concept of property descriptors. Freezing an object with private properties does not prevent the values of these private properties from being changed. (Freezing objects is usually meant as a security measure against external code, but external code cannot access private properties anyway.) Private properties cannot be added or removed from the object, whether the object is frozen or not.
`freeze()` returns the same object that was passed into the function. It
_does not_ create a frozen copy.
A {{jsxref("TypedArray")}} or a {{jsxref("DataView")}} with elements will cause a {{jsxref("TypeError")}},
as they are views over memory and will definitely cause other possible issues:
```js
Object.freeze(new Uint8Array(0)); // No elements
// Uint8Array []
Object.freeze(new Uint8Array(1)); // Has elements
// TypeError: Cannot freeze array buffer views with elements
Object.freeze(new DataView(new ArrayBuffer(32))); // No elements
// DataView {}
Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)); // No elements
// Float64Array []
Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)); // Has elements
// TypeError: Cannot freeze array buffer views with elements
```
Note that as the standard three properties (`buf.byteLength`,
`buf.byteOffset` and `buf.buffer`) are read-only (as are those of
an {{jsxref("ArrayBuffer")}} or {{jsxref("SharedArrayBuffer")}}), there is no reason for
attempting to freeze these properties.
Unlike {{jsxref("Object.seal()")}}, existing properties in objects frozen with `Object.freeze()` are made immutable and data properties cannot be re-assigned.
## Examples
### Freezing objects
```js
const obj = {
prop() {},
foo: "bar",
};
// Before freezing: new properties may be added,
// and existing properties may be changed or removed
obj.foo = "baz";
obj.lumpy = "woof";
delete obj.prop;
// Freeze.
const o = Object.freeze(obj);
// The return value is just the same object we passed in.
o === obj; // true
// The object has become frozen.
Object.isFrozen(obj); // === true
// Now any changes will fail
obj.foo = "quux"; // silently does nothing
// silently doesn't add the property
obj.quaxxor = "the friendly duck";
// In strict mode such attempts will throw TypeErrors
function fail() {
"use strict";
obj.foo = "sparky"; // throws a TypeError
delete obj.foo; // throws a TypeError
delete obj.quaxxor; // returns true since attribute 'quaxxor' was never added
obj.sparky = "arf"; // throws a TypeError
}
fail();
// Attempted changes through Object.defineProperty;
// both statements below throw a TypeError.
Object.defineProperty(obj, "ohai", { value: 17 });
Object.defineProperty(obj, "foo", { value: "eit" });
// It's also impossible to change the prototype
// both statements below will throw a TypeError.
Object.setPrototypeOf(obj, { x: 20 });
obj.__proto__ = { x: 20 };
```
### Freezing arrays
```js
const a = [0];
Object.freeze(a); // The array cannot be modified now.
a[0] = 1; // fails silently
// In strict mode such attempt will throw a TypeError
function fail() {
"use strict";
a[0] = 1;
}
fail();
// Attempted to push
a.push(2); // throws a TypeError
```
The object being frozen is _immutable_. However, it is not necessarily
_constant_. The following example shows that a frozen object is not constant
(freeze is shallow).
```js
const obj1 = {
internal: {},
};
Object.freeze(obj1);
obj1.internal.a = "aValue";
obj1.internal.a; // 'aValue'
```
To be a constant object, the entire reference graph (direct and indirect references to
other objects) must reference only immutable frozen objects. The object being frozen is
said to be immutable because the entire object _state_ (values and references to
other objects) within the whole object is fixed. Note that strings, numbers, and
booleans are always immutable and that Functions and Arrays are objects.
#### What is "shallow freeze"?
The result of calling `Object.freeze(object)` only applies to the
immediate properties of `object` itself and will prevent future property
addition, removal or value re-assignment operations _only_ on
`object`. If the value of those properties are objects themselves, those
objects are not frozen and may be the target of property addition, removal or value
re-assignment operations.
```js
const employee = {
name: "Mayank",
designation: "Developer",
address: {
street: "Rohini",
city: "Delhi",
},
};
Object.freeze(employee);
employee.name = "Dummy"; // fails silently in non-strict mode
employee.address.city = "Noida"; // attributes of child object can be modified
console.log(employee.address.city); // "Noida"
```
To make an object immutable, recursively freeze each non-primitive property
(deep freeze). Use the pattern on a case-by-case basis based on your design when you
know the object contains no [cycles](<https://en.wikipedia.org/wiki/Cycle_(graph_theory)>) in the reference
graph, otherwise an endless loop will be triggered. An enhancement to
`deepFreeze()` would be to have an internal function that receives a path
(e.g. an Array) argument so you can suppress calling `deepFreeze()`
recursively when an object is in the process of being made immutable. You still run a
risk of freezing an object that shouldn't be frozen, such as [`window`](/en-US/docs/Web/API/Window).
```js
function deepFreeze(object) {
// Retrieve the property names defined on object
const propNames = Reflect.ownKeys(object);
// Freeze properties before freezing self
for (const name of propNames) {
const value = object[name];
if ((value && typeof value === "object") || typeof value === "function") {
deepFreeze(value);
}
}
return Object.freeze(object);
}
const obj2 = {
internal: {
a: null,
},
};
deepFreeze(obj2);
obj2.internal.a = "anotherValue"; // fails silently in non-strict mode
obj2.internal.a; // null
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Object.isFrozen()")}}
- {{jsxref("Object.preventExtensions()")}}
- {{jsxref("Object.isExtensible()")}}
- {{jsxref("Object.seal()")}}
- {{jsxref("Object.isSealed()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/__lookupsetter__/index.md | ---
title: Object.prototype.__lookupSetter__()
slug: Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.Object.lookupSetter
---
{{JSRef}} {{Deprecated_Header}}
> **Note:** This feature is deprecated in favor of the {{jsxref("Object.getOwnPropertyDescriptor()")}} API. This method's behavior is only specified for web compatibility, and is not required to be implemented in any platform. It may not work everywhere.
The **`__lookupSetter__()`** method of {{jsxref("Object")}} instances returns the function bound as a setter to the specified property.
## Syntax
```js-nolint
__lookupSetter__(prop)
```
### Parameters
- `prop`
- : A string containing the name of the property whose setter should be returned.
### Return value
The function bound as a setter to the specified property. Returns `undefined` if no such property is found, or the property is a [data property](/en-US/docs/Web/JavaScript/Data_structures#data_property).
## Description
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `__lookupSetter__()` method. If a [setter](/en-US/docs/Web/JavaScript/Reference/Functions/get) has been defined for an object's property, it's not possible to reference the setter function through that property, because that property only calls the function when it's being set. `__lookupSetter__()` can be used to obtain a reference to the setter function.
`__lookupSetter__()` walks up the [prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) to find the specified property. If any object along the prototype chain has the specified [own property](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn), the `set` attribute of the [property descriptor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor) for that property is returned. If that property is a data property, `undefined` is returned. If the property is not found along the entire prototype chain, `undefined` is also returned.
`__lookupSetter__()` is defined in the spec as "normative optional", which means no implementation is required to implement this. However, all major browsers implement it, and due to its continued usage, it's unlikely to be removed. If a browser implements `__lookupSetter__()`, it also needs to implement the [`__lookupGetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__), [`__defineGetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__), and [`__defineSetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__) methods.
## Examples
### Using \_\_lookupSetter\_\_()
```js
const obj = {
set foo(value) {
this.bar = value;
},
};
obj.__lookupSetter__("foo");
// [Function: set foo]
```
### Looking up a property's setter in the standard way
You should use the {{jsxref("Object.getOwnPropertyDescriptor()")}} API to look up a property's setter. Compared to `__lookupSetter__()`, this method allows looking up [symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) properties. The `Object.getOwnPropertyDescriptor()` method also works with [`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), which don't inherit from `Object.prototype` and therefore don't have the `__lookupSetter__()` method. If `__lookupSetter__()`'s behavior of walking up the prototype chain is important, you may implement it yourself with {{jsxref("Object.getPrototypeOf()")}}.
```js
const obj = {
set foo(value) {
this.bar = value;
},
};
Object.getOwnPropertyDescriptor(obj, "foo").set;
// [Function: set foo]
```
```js
const obj2 = {
__proto__: {
set foo(value) {
this.bar = value;
},
},
};
function findSetter(obj, prop) {
while (obj) {
const desc = Object.getOwnPropertyDescriptor(obj, prop);
if (desc) {
return desc.set;
}
obj = Object.getPrototypeOf(obj);
}
}
console.log(findSetter(obj2, "foo")); // [Function: set foo]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.prototype.__lookupSetter__` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- [`Object.prototype.__lookupGetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__)
- {{jsxref("Functions/set", "set")}}
- {{jsxref("Object.getOwnPropertyDescriptor()")}}
- [`Object.prototype.__defineGetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__)
- [`Object.prototype.__defineSetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__)
- [JS Guide: Defining Getters and Setters](/en-US/docs/Web/JavaScript/Guide/Working_with_objects#defining_getters_and_setters)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/isfrozen/index.md | ---
title: Object.isFrozen()
slug: Web/JavaScript/Reference/Global_Objects/Object/isFrozen
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.isFrozen
---
{{JSRef}}
The **`Object.isFrozen()`** static method determines if an object is
{{jsxref("Object/freeze", "frozen", "", 1)}}.
{{EmbedInteractiveExample("pages/js/object-isfrozen.html")}}
## Syntax
```js-nolint
Object.isFrozen(obj)
```
### Parameters
- `obj`
- : The object which should be checked.
### Return value
A {{jsxref("Boolean")}} indicating whether or not the given object is frozen.
## Description
An object is frozen if and only if it is not [extensible](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible), all its properties are non-configurable, and all its data
properties (that is, properties which are not accessor properties with getter or setter
components) are non-writable.
## Examples
### Using Object.isFrozen
```js
// A new object is extensible, so it is not frozen.
Object.isFrozen({}); // false
// An empty object which is not extensible
// is vacuously frozen.
const vacuouslyFrozen = Object.preventExtensions({});
Object.isFrozen(vacuouslyFrozen); // true
// A new object with one property is also extensible,
// ergo not frozen.
const oneProp = { p: 42 };
Object.isFrozen(oneProp); // false
// Preventing extensions to the object still doesn't
// make it frozen, because the property is still
// configurable (and writable).
Object.preventExtensions(oneProp);
Object.isFrozen(oneProp); // false
// Deleting that property makes the object vacuously frozen.
delete oneProp.p;
Object.isFrozen(oneProp); // true
// A non-extensible object with a non-writable
// but still configurable property is not frozen.
const nonWritable = { e: "plep" };
Object.preventExtensions(nonWritable);
Object.defineProperty(nonWritable, "e", {
writable: false,
}); // make non-writable
Object.isFrozen(nonWritable); // false
// Changing that property to non-configurable
// then makes the object frozen.
Object.defineProperty(nonWritable, "e", {
configurable: false,
}); // make non-configurable
Object.isFrozen(nonWritable); // true
// A non-extensible object with a non-configurable
// but still writable property also isn't frozen.
const nonConfigurable = { release: "the kraken!" };
Object.preventExtensions(nonConfigurable);
Object.defineProperty(nonConfigurable, "release", {
configurable: false,
});
Object.isFrozen(nonConfigurable); // false
// Changing that property to non-writable
// then makes the object frozen.
Object.defineProperty(nonConfigurable, "release", {
writable: false,
});
Object.isFrozen(nonConfigurable); // true
// A non-extensible object with a configurable
// accessor property isn't frozen.
const accessor = {
get food() {
return "yum";
},
};
Object.preventExtensions(accessor);
Object.isFrozen(accessor); // false
// When we make that property non-configurable it becomes frozen.
Object.defineProperty(accessor, "food", {
configurable: false,
});
Object.isFrozen(accessor); // true
// But the easiest way for an object to be frozen
// is if Object.freeze has been called on it.
const frozen = { 1: 81 };
Object.isFrozen(frozen); // false
Object.freeze(frozen);
Object.isFrozen(frozen); // true
// By definition, a frozen object is non-extensible.
Object.isExtensible(frozen); // false
// Also by definition, a frozen object is sealed.
Object.isSealed(frozen); // true
```
### Non-object argument
In ES5, if the argument to this method is not an object (a primitive), then it will cause a {{jsxref("TypeError")}}. In ES2015, it will return `true` without any errors if a non-object argument is passed, since primitives are, by definition, immutable.
```js
Object.isFrozen(1);
// TypeError: 1 is not an object (ES5 code)
Object.isFrozen(1);
// true (ES2015 code)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Object.freeze()")}}
- {{jsxref("Object.preventExtensions()")}}
- {{jsxref("Object.isExtensible()")}}
- {{jsxref("Object.seal()")}}
- {{jsxref("Object.isSealed()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/valueof/index.md | ---
title: Object.prototype.valueOf()
slug: Web/JavaScript/Reference/Global_Objects/Object/valueOf
page-type: javascript-instance-method
browser-compat: javascript.builtins.Object.valueOf
---
{{JSRef}}
The **`valueOf()`** method of {{jsxref("Object")}} instances converts the `this` value [to an object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion). This method is meant to be overridden by derived objects for custom [type conversion](/en-US/docs/Web/JavaScript/Data_structures#type_coercion) logic.
{{EmbedInteractiveExample("pages/js/object-prototype-valueof.html")}}
## Syntax
```js-nolint
valueOf()
```
### Parameters
None.
### Return value
The `this` value, converted to an object.
> **Note:** In order for `valueOf` to be useful during type conversion, it must return a primitive. Because all primitive types have their own `valueOf()` methods, calling `aPrimitiveValue.valueOf()` generally does not invoke `Object.prototype.valueOf()`.
## Description
JavaScript calls the `valueOf` method to [convert an object to a primitive value](/en-US/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `valueOf` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.
This method is called in priority by [numeric conversion](/en-US/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion), but [string conversion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) calls `toString()` in priority, and `toString()` is very likely to return a string value (even for the {{jsxref("Object.prototype.toString()")}} base implementation), so `valueOf()` is usually not called in this case.
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. The `Object.prototype.valueOf()` base implementation is deliberately useless: by returning an object, its return value will never be used by any [primitive conversion algorithm](/en-US/docs/Web/JavaScript/Data_structures#type_coercion). Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override `valueOf()` to call a custom method, so that your custom object can be converted to a primitive value. Generally, `valueOf()` is used to return a value that is most meaningful for the object — unlike `toString()`, it does not need to be a string. Alternatively, you can add a [`@@toPrimitive`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion.
## Examples
### Using valueOf()
The base `valueOf()` method returns the `this` value itself, converted to an object if it isn't already. Therefore its return value will never be used by any primitive conversion algorithm.
```js
const obj = { foo: 1 };
console.log(obj.valueOf() === obj); // true
console.log(Object.prototype.valueOf.call("primitive"));
// [String: 'primitive'] (a wrapper object)
```
### Overriding valueOf for custom objects
You can create a function to be called in place of the default `valueOf` method. Your function should take no arguments, since it won't be passed any when called during type conversion.
For example, you can add a `valueOf` method to your custom class `Box`.
```js
class Box {
#value;
constructor(value) {
this.#value = value;
}
valueOf() {
return this.#value;
}
}
```
With the preceding code in place, any time an object of type `Box` is used in a context where it is to be represented as a primitive value (but not specifically a string), JavaScript automatically calls the function defined in the preceding code.
```js
const box = new Box(123);
console.log(box + 456); // 579
console.log(box == 123); // true
```
An object's `valueOf` method is usually invoked by JavaScript, but you can invoke it yourself as follows:
```js
box.valueOf();
```
### Using unary plus on objects
[Unary plus](/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus) performs [number coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) on its operand, which, for most objects without [`@@toPrimitive`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive), means calling its `valueOf()`. However, if the object doesn't have a custom `valueOf()` method, the base implementation will cause `valueOf()` to be ignored and the return value of `toString()` to be used instead.
```js
+new Date(); // the current timestamp; same as new Date().getTime()
+{}; // NaN (toString() returns "[object Object]")
+[]; // 0 (toString() returns an empty string list)
+[1]; // 1 (toString() returns "1")
+[1, 2]; // NaN (toString() returns "1,2")
+new Set([1]); // NaN (toString() returns "[object Set]")
+{ valueOf: () => 42 }; // 42
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Object.prototype.toString()")}}
- {{jsxref("parseInt()")}}
- {{jsxref("Symbol.toPrimitive")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/constructor/index.md | ---
title: Object.prototype.constructor
slug: Web/JavaScript/Reference/Global_Objects/Object/constructor
page-type: javascript-instance-data-property
browser-compat: javascript.builtins.Object.constructor
---
{{JSRef}}
The **`constructor`** data property of an {{jsxref("Object")}} instance returns a reference to the constructor function that created the instance object. Note that the value of this property is a reference to _the function itself_, not a string containing the function's name.
> **Note:** This is a property of JavaScript objects. For the `constructor` method in classes, see [its own reference page](/en-US/docs/Web/JavaScript/Reference/Classes/constructor).
## Value
A reference to the constructor function that created the instance object.
{{js_property_attributes(1, 0, 1)}}
> **Note:** This property is created by default on the [`prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype) property of every constructor function and is inherited by all objects created by that constructor.
## Description
Any object (with the exception of [`null` prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) will have a `constructor` property on its `[[Prototype]]`. Objects created with literals will also have a `constructor` property that points to the constructor type for that object — for example, array literals create {{jsxref("Array")}} objects, and [object literals](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) create plain objects.
```js
const o1 = {};
o1.constructor === Object; // true
const o2 = new Object();
o2.constructor === Object; // true
const a1 = [];
a1.constructor === Array; // true
const a2 = new Array();
a2.constructor === Array; // true
const n = 3;
n.constructor === Number; // true
```
Note that `constructor` usually comes from the constructor's [`prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype) property. If you have a longer prototype chain, you can usually expect every object in the chain to have a `constructor` property.
```js
const o = new TypeError(); // Inheritance: TypeError -> Error -> Object
const proto = Object.getPrototypeOf;
Object.hasOwn(o, "constructor"); // false
proto(o).constructor === TypeError; // true
proto(proto(o)).constructor === Error; // true
proto(proto(proto(o))).constructor === Object; // true
```
## Examples
### Displaying the constructor of an object
The following example creates a constructor (`Tree`) and an object of that type (`theTree`). The example then displays the `constructor` property for the object `theTree`.
```js
function Tree(name) {
this.name = name;
}
const theTree = new Tree("Redwood");
console.log(`theTree.constructor is ${theTree.constructor}`);
```
This example displays the following output:
```plain
theTree.constructor is function Tree(name) {
this.name = name;
}
```
### Assigning the constructor property to an object
One can assign the `constructor` property of non-primitives.
```js
const arr = [];
arr.constructor = String;
arr.constructor === String; // true
arr instanceof String; // false
arr instanceof Array; // true
const foo = new Foo();
foo.constructor = "bar";
foo.constructor === "bar"; // true
// etc.
```
This does not overwrite the old `constructor` property — it was originally present on the instance's `[[Prototype]]`, not as its own property.
```js
const arr = [];
Object.hasOwn(arr, "constructor"); // false
Object.hasOwn(Object.getPrototypeOf(arr), "constructor"); // true
arr.constructor = String;
Object.hasOwn(arr, "constructor"); // true — the instance property shadows the one on its prototype
```
But even when `Object.getPrototypeOf(a).constructor` is re-assigned, it won't change other behaviors of the object. For example, the behavior of `instanceof` is controlled by [`Symbol.hasInstance`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance), not `constructor`:
```js
const arr = [];
arr.constructor = String;
arr instanceof String; // false
arr instanceof Array; // true
```
There is nothing protecting the `constructor` property from being re-assigned or shadowed, so using it to detect the type of a variable should usually be avoided in favor of less fragile ways like `instanceof` and [`Symbol.toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) for objects, or [`typeof`](/en-US/docs/Web/JavaScript/Reference/Operators/typeof) for primitives.
### Changing the constructor of a constructor function's prototype
Every constructor has a [`prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype) property, which will become the instance's `[[Prototype]]` when called via the [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) operator. `ConstructorFunction.prototype.constructor` will therefore become a property on the instance's `[[Prototype]]`, as previously demonstrated.
However, if `ConstructorFunction.prototype` is re-assigned, the `constructor` property will be lost. For example, the following is a common way to create an inheritance pattern:
```js
function Parent() {
// …
}
Parent.prototype.parentMethod = function () {};
function Child() {
Parent.call(this); // Make sure everything is initialized properly
}
// Pointing the [[Prototype]] of Child.prototype to Parent.prototype
Child.prototype = Object.create(Parent.prototype);
```
The `constructor` of instances of `Child` will be `Parent` due to `Child.prototype` being re-assigned.
This is usually not a big deal — the language almost never reads the `constructor` property of an object. The only exception is when using [`@@species`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/species) to create new instances of a class, but such cases are rare, and you should be using the [`extends`](/en-US/docs/Web/JavaScript/Reference/Classes/extends) syntax to subclass builtins anyway.
However, ensuring that `Child.prototype.constructor` always points to `Child` itself is crucial when some caller is using `constructor` to access the original class from an instance. Take the following case: the object has the `create()` method to create itself.
```js
function Parent() {
// …
}
function CreatedConstructor() {
Parent.call(this);
}
CreatedConstructor.prototype = Object.create(Parent.prototype);
CreatedConstructor.prototype.create = function () {
return new this.constructor();
};
new CreatedConstructor().create().create(); // TypeError: new CreatedConstructor().create().create is undefined, since constructor === Parent
```
In the example above, an exception is thrown, since the `constructor` links to `Parent`. To avoid this, just assign the necessary constructor you are going to use.
```js
function Parent() {
// …
}
function CreatedConstructor() {
// …
}
CreatedConstructor.prototype = Object.create(Parent.prototype, {
// Return original constructor to Child
constructor: {
value: CreatedConstructor,
enumerable: false, // Make it non-enumerable, so it won't appear in `for...in` loop
writable: true,
configurable: true,
},
});
CreatedConstructor.prototype.create = function () {
return new this.constructor();
};
new CreatedConstructor().create().create(); // it's pretty fine
```
Note that when manually adding the `constructor` property, it's crucial to make the property [non-enumerable](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties), so `constructor` won't be visited in [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loops — as it normally isn't.
If the code above looks like too much boilerplate, you may also consider using [`Object.setPrototypeOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf) to manipulate the prototype chain.
```js
function Parent() {
// …
}
function CreatedConstructor() {
// …
}
Object.setPrototypeOf(CreatedConstructor.prototype, Parent.prototype);
CreatedConstructor.prototype.create = function () {
return new this.constructor();
};
new CreatedConstructor().create().create(); // still works without re-creating constructor property
```
`Object.setPrototypeOf()` comes with its potential performance downsides because all previously created objects involved in the prototype chain have to be re-compiled; but if the above initialization code happens before `Parent` or `CreatedConstructor` are constructed, the effect should be minimal.
Let's consider one more involved case.
```js
function ParentWithStatic() {}
ParentWithStatic.startPosition = { x: 0, y: 0 }; // Static member property
ParentWithStatic.getStartPosition = function () {
return this.startPosition;
};
function Child(x, y) {
this.position = { x, y };
}
Child.prototype = Object.create(ParentWithStatic.prototype, {
// Return original constructor to Child
constructor: {
value: Child,
enumerable: false,
writable: true,
configurable: true,
},
});
Child.prototype.getOffsetByInitialPosition = function () {
const position = this.position;
// Using this.constructor, in hope that getStartPosition exists as a static method
const startPosition = this.constructor.getStartPosition();
return {
offsetX: startPosition.x - position.x,
offsetY: startPosition.y - position.y,
};
};
new Child(1, 1).getOffsetByInitialPosition();
// Error: this.constructor.getStartPosition is undefined, since the
// constructor is Child, which doesn't have the getStartPosition static method
```
For this example to work properly, we can reassign the `Parent`'s static properties to `Child`:
```js
// …
Object.assign(Child, ParentWithStatic); // Notice that we assign it before we create() a prototype below
Child.prototype = Object.create(ParentWithStatic.prototype, {
// Return original constructor to Child
constructor: {
value: Child,
enumerable: false,
writable: true,
configurable: true,
},
});
// …
```
But even better, we can make the constructor functions themselves extend each other, as classes' [`extends`](/en-US/docs/Web/JavaScript/Reference/Classes/extends) do.
```js
function ParentWithStatic() {}
ParentWithStatic.startPosition = { x: 0, y: 0 }; // Static member property
ParentWithStatic.getStartPosition = function () {
return this.startPosition;
};
function Child(x, y) {
this.position = { x, y };
}
// Properly create inheritance!
Object.setPrototypeOf(Child.prototype, ParentWithStatic.prototype);
Object.setPrototypeOf(Child, ParentWithStatic);
Child.prototype.getOffsetByInitialPosition = function () {
const position = this.position;
const startPosition = this.constructor.getStartPosition();
return {
offsetX: startPosition.x - position.x,
offsetY: startPosition.y - position.y,
};
};
console.log(new Child(1, 1).getOffsetByInitialPosition()); // { offsetX: -1, offsetY: -1 }
```
Again, using `Object.setPrototypeOf()` may have adverse performance effects, so make sure it happens immediately after the constructor declaration and before any instances are created — to avoid objects being "tainted".
> **Note:** Manually updating or setting the constructor can lead to different and sometimes confusing consequences. To prevent this, just define the role of `constructor` in each specific case. In most cases, `constructor` is not used and reassigning it is not necessary.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/class", "class")}}
- {{jsxref("Classes/constructor", "constructor")}}
- {{Glossary("Constructor")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/preventextensions/index.md | ---
title: Object.preventExtensions()
slug: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.preventExtensions
---
{{JSRef}}
The **`Object.preventExtensions()`** static method prevents new
properties from ever being added to an object (i.e. prevents future extensions to the
object). It also prevents the object's prototype from being re-assigned.
{{EmbedInteractiveExample("pages/js/object-preventextensions.html")}}
## Syntax
```js-nolint
Object.preventExtensions(obj)
```
### Parameters
- `obj`
- : The object which should be made non-extensible.
### Return value
The object being made non-extensible.
## Description
An object is extensible if new properties can be added to it.
`Object.preventExtensions()` marks an object as no longer extensible, so that
it will never have properties beyond the ones it had at the time it was marked as
non-extensible. Note that the properties of a non-extensible object, in general, may
still be _deleted_. Attempting to add new properties to a non-extensible object
will fail, either silently or, in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), throwing a {{jsxref("TypeError")}}.
Unlike [`Object.seal()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal) and [`Object.freeze()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), `Object.preventExtensions()` invokes an intrinsic JavaScript behavior and cannot be replaced with a composition of several other operations. It also has its `Reflect` counterpart (which only exists for intrinsic operations), [`Reflect.preventExtensions()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions).
`Object.preventExtensions()` only prevents addition of own properties. Properties can still be added to the object prototype.
This method makes the `[[Prototype]]` of the target immutable; any `[[Prototype]]` re-assignment will throw a `TypeError`. This behavior is specific to the internal `[[Prototype]]` property; other properties of the target object will remain mutable.
There is no way to make an object extensible again once it has been made non-extensible.
## Examples
### Using Object.preventExtensions
```js
// Object.preventExtensions returns the object
// being made non-extensible.
const obj = {};
const obj2 = Object.preventExtensions(obj);
obj === obj2; // true
// Objects are extensible by default.
const empty = {};
Object.isExtensible(empty); // true
// They can be made un-extensible
Object.preventExtensions(empty);
Object.isExtensible(empty); // false
// Object.defineProperty throws when adding
// a new property to a non-extensible object.
const nonExtensible = { removable: true };
Object.preventExtensions(nonExtensible);
Object.defineProperty(nonExtensible, "new", {
value: 8675309,
}); // throws a TypeError
// In strict mode, attempting to add new properties
// to a non-extensible object throws a TypeError.
function fail() {
"use strict";
// throws a TypeError
nonExtensible.newProperty = "FAIL";
}
fail();
```
A non-extensible object's prototype is immutable:
```js
const fixed = Object.preventExtensions({});
// throws a 'TypeError'.
fixed.__proto__ = { oh: "hai" };
```
### Non-object argument
In ES5, if the argument to this method is not an object (a primitive), then it will cause a {{jsxref("TypeError")}}. In ES2015, a non-object argument will be returned as-is without any errors, since primitives are already, by definition, immutable.
```js
Object.preventExtensions(1);
// TypeError: 1 is not an object (ES5 code)
Object.preventExtensions(1);
// 1 (ES2015 code)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Object.isExtensible()")}}
- {{jsxref("Object.seal()")}}
- {{jsxref("Object.isSealed()")}}
- {{jsxref("Object.freeze()")}}
- {{jsxref("Object.isFrozen()")}}
- {{jsxref("Reflect.preventExtensions()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/object/index.md | ---
title: Object() constructor
slug: Web/JavaScript/Reference/Global_Objects/Object/Object
page-type: javascript-constructor
browser-compat: javascript.builtins.Object.Object
---
{{JSRef}}
The **`Object()`** constructor turns the input into an object. Its behavior depends on the input's type.
## Syntax
```js-nolint
new Object()
new Object(value)
Object()
Object(value)
```
> **Note:** `Object()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new), but sometimes with different effects. See [Return value](#return_value).
### Parameters
- `value` {{optional_inline}}
- : Any value.
### Return value
When the `Object()` constructor itself is called or constructed, its return value is an object:
- If the value is [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) or {{jsxref("undefined")}}, it creates and returns an empty object.
- If the value is an object already, it returns the value.
- Otherwise, it returns an object of a type that corresponds to the given value. For example, passing a {{jsxref("BigInt")}} primitive returns a `BigInt` wrapper object.
When `Object()` is constructed but [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target) is not the `Object` constructor itself, the behavior is slightly different — it initializes a new object with `new.target.prototype` as its prototype. Any argument value is ignored. This may happen, for example, when `Object()` is implicitly called via [`super()`](/en-US/docs/Web/JavaScript/Reference/Operators/super) in the constructor of a class that [extends `Object`](/en-US/docs/Web/JavaScript/Reference/Classes/extends#extending_object). In this case, even if you pass a number to `super()`, the `this` value inside the constructor does not become a {{jsxref("Number")}} instance.
## Examples
### Creating a new Object
```js
const o = new Object();
o.foo = 42;
console.log(o);
// { foo: 42 }
```
### Using Object given undefined and null types
The following examples store an empty `Object` object in `o`:
```js
const o = new Object();
```
```js
const o = new Object(undefined);
```
```js
const o = new Object(null);
```
### Obtaining wrapper objects for BigInt and Symbol
The {{jsxref("BigInt/BigInt", "BigInt()")}} and {{jsxref("Symbol/Symbol", "Symbol()")}} constructors throw an error when called with `new`, to prevent the common mistake of creating a wrapper object instead of the primitive value. The only way to create a wrapper object for these types is to call `Object()` with them:
```js
const numberObj = new Number(1);
console.log(typeof numberObj); // "object"
const bigintObj = Object(1n);
console.log(typeof bigintObj); // "object"
const symbolObj = Object(Symbol("foo"));
console.log(typeof symbolObj); // "object"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/tolocalestring/index.md | ---
title: Object.prototype.toLocaleString()
slug: Web/JavaScript/Reference/Global_Objects/Object/toLocaleString
page-type: javascript-instance-method
browser-compat: javascript.builtins.Object.toLocaleString
---
{{JSRef}}
The **`toLocaleString()`** method of {{jsxref("Object")}} instances returns a string representing this object. This method is meant to be overridden by derived objects for locale-specific purposes.
{{EmbedInteractiveExample("pages/js/object-prototype-tolocalestring.html")}}
## Syntax
```js-nolint
toLocaleString()
```
### Parameters
None. However, all objects that override this method are expected to accept at most two parameters, corresponding to `locales` and `options`, such as {{jsxref("Date.prototype.toLocaleString")}}. The parameter positions should not be used for any other purpose.
### Return value
The return value of calling `this.toString()`.
## Description
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toLocaleString()` method. {{jsxref("Object")}}'s `toLocaleString` returns the result of calling {{jsxref("Object/toString", "this.toString()")}}.
This function is provided to give objects a generic `toLocaleString` method, even though not all may use it. In the core language, these built-in objects override `toLocaleString` to provide locale-specific formatting:
- {{jsxref("Array")}}: {{jsxref("Array.prototype.toLocaleString()")}}
- {{jsxref("Number")}}: {{jsxref("Number.prototype.toLocaleString()")}}
- {{jsxref("Date")}}: {{jsxref("Date.prototype.toLocaleString()")}}
- {{jsxref("TypedArray")}}: {{jsxref("TypedArray.prototype.toLocaleString()")}}
- {{jsxref("BigInt")}}: {{jsxref("BigInt.prototype.toLocaleString()")}}
## Examples
### Using the base toLocaleString() method
The base `toLocaleString()` method simply calls `toString()`.
```js
const obj = {
toString() {
return "My Object";
},
};
console.log(obj.toLocaleString()); // "My Object"
```
### Array toLocaleString() override
{{jsxref("Array.prototype.toLocaleString()")}} is used to print array values as a string by invoking each element's `toLocaleString()` method and joining the results with a locale-specific separator. For example:
```js
const testArray = [4, 7, 10];
const euroPrices = testArray.toLocaleString("fr", {
style: "currency",
currency: "EUR",
});
// "4,00 €,7,00 €,10,00 €"
```
### Date toLocaleString() override
{{jsxref("Date.prototype.toLocaleString()")}} is used to print out date displays more suitable for specific locales. For example:
```js
const testDate = new Date();
// "Fri May 29 2020 18:04:24 GMT+0100 (British Summer Time)"
const deDate = testDate.toLocaleString("de");
// "29.5.2020, 18:04:24"
const frDate = testDate.toLocaleString("fr");
// "29/05/2020, 18:04:24"
```
### Number toLocaleString() override
{{jsxref("Number.prototype.toLocaleString()")}} is used to print out number displays more suitable for specific locales, e.g. with the correct separators. For example:
```js
const testNumber = 2901234564;
// "2901234564"
const deNumber = testNumber.toLocaleString("de");
// "2.901.234.564"
const frNumber = testNumber.toLocaleString("fr");
// "2 901 234 564"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Object.prototype.toString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/__lookupgetter__/index.md | ---
title: Object.prototype.__lookupGetter__()
slug: Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.Object.lookupGetter
---
{{JSRef}} {{Deprecated_Header}}
> **Note:** This feature is deprecated in favor of the {{jsxref("Object.getOwnPropertyDescriptor()")}} API. This method's behavior is only specified for web compatibility, and is not required to be implemented in any platform. It may not work everywhere.
The **`__lookupGetter__()`** method of {{jsxref("Object")}} instances returns the function bound as a getter to the specified property.
## Syntax
```js-nolint
__lookupGetter__(prop)
```
### Parameters
- `prop`
- : A string containing the name of the property whose getter should be returned.
### Return value
The function bound as a getter to the specified property. Returns `undefined` if no such property is found, or the property is a [data property](/en-US/docs/Web/JavaScript/Data_structures#data_property).
## Description
All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `__lookupGetter__()` method. If a [getter](/en-US/docs/Web/JavaScript/Reference/Functions/get) has been defined for an object's property, it's not possible to reference the getter function through that property, because that property refers to the return value of that function. `__lookupGetter__()` can be used to obtain a reference to the getter function.
`__lookupGetter__()` walks up the [prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) to find the specified property. If any object along the prototype chain has the specified [own property](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn), the `get` attribute of the [property descriptor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor) for that property is returned. If that property is a data property, `undefined` is returned. If the property is not found along the entire prototype chain, `undefined` is also returned.
`__lookupGetter__()` is defined in the spec as "normative optional", which means no implementation is required to implement this. However, all major browsers implement it, and due to its continued usage, it's unlikely to be removed. If a browser implements `__lookupGetter__()`, it also needs to implement the [`__lookupSetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__), [`__defineGetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__), and [`__defineSetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__) methods.
## Examples
### Using \_\_lookupGetter\_\_()
```js
const obj = {
get foo() {
return Math.random() > 0.5 ? "foo" : "bar";
},
};
obj.__lookupGetter__("foo");
// [Function: get foo]
```
### Looking up a property's getter in the standard way
You should use the {{jsxref("Object.getOwnPropertyDescriptor()")}} API to look up a property's getter. Compared to `__lookupGetter__()`, this method allows looking up [symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) properties. The `Object.getOwnPropertyDescriptor()` method also works with [`null`-prototype objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), which don't inherit from `Object.prototype` and therefore don't have the `__lookupGetter__()` method. If `__lookupGetter__()`'s behavior of walking up the prototype chain is important, you may implement it yourself with {{jsxref("Object.getPrototypeOf()")}}.
```js
const obj = {
get foo() {
return Math.random() > 0.5 ? "foo" : "bar";
},
};
Object.getOwnPropertyDescriptor(obj, "foo").get;
// [Function: get foo]
```
```js
const obj2 = {
__proto__: {
get foo() {
return Math.random() > 0.5 ? "foo" : "bar";
},
},
};
function findGetter(obj, prop) {
while (obj) {
const desc = Object.getOwnPropertyDescriptor(obj, prop);
if (desc) {
return desc.get;
}
obj = Object.getPrototypeOf(obj);
}
}
console.log(findGetter(obj2, "foo")); // [Function: get foo]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.prototype.__lookupGetter__` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- [`Object.prototype.__lookupSetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__)
- {{jsxref("Functions/get", "get")}}
- {{jsxref("Object.getOwnPropertyDescriptor()")}}
- [`Object.prototype.__defineGetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__)
- [`Object.prototype.__defineSetter__()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__)
- [JS Guide: Defining Getters and Setters](/en-US/docs/Web/JavaScript/Guide/Working_with_objects#defining_getters_and_setters)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/defineproperty/index.md | ---
title: Object.defineProperty()
slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperty
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.defineProperty
---
{{JSRef}}
The **`Object.defineProperty()`** static method defines a new property directly on an object, or modifies an existing property on an object, and returns the object.
{{EmbedInteractiveExample("pages/js/object-defineproperty.html")}}
## Syntax
```js-nolint
Object.defineProperty(obj, prop, descriptor)
```
### Parameters
- `obj`
- : The object on which to define the property.
- `prop`
- : A string or {{jsxref("Symbol")}} specifying the key of the property to be defined or modified.
- `descriptor`
- : The descriptor for the property being defined or modified.
### Return value
The object that was passed to the function, with the specified property added or modified.
## Description
`Object.defineProperty()` allows a precise addition to or modification of a property on an object. Normal property addition through [assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Assignment) creates properties which show up during property enumeration ({{jsxref("Statements/for...in", "for...in")}}, {{jsxref("Object.keys()")}}, etc.), whose values may be changed and which may be {{jsxref("Operators/delete", "deleted", "", 1)}}. This method allows these extra details to be changed from their defaults. By default, properties added using `Object.defineProperty()` are not writable, not enumerable, and not configurable. In addition, `Object.defineProperty()` uses the [`[[DefineOwnProperty]]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/defineProperty) internal method, instead of [`[[Set]]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/set), so it does not invoke [setters](/en-US/docs/Web/JavaScript/Reference/Functions/set), even when the property is already present.
Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A **data descriptor** is a property with a value that may or may not be writable. An **accessor descriptor** is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.
Both data and accessor descriptors are objects. They share the following optional keys (please note: the **defaults** mentioned here are in the case of defining properties using `Object.defineProperty()`):
- `configurable`
- : when this is set to `false`,
- the type of this property cannot be changed between data property and accessor property, and
- the property may not be deleted, and
- other attributes of its descriptor cannot be changed (however, if it's a data descriptor with `writable: true`, the `value` can be changed, and `writable` can be changed to `false`).
**Defaults to `false`.**
- `enumerable`
- : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.**
A **data descriptor** also has the following optional keys:
- `value`
- : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to {{jsxref("undefined")}}.**
- `writable`
- : `true` if the value associated with the property may be changed with an [assignment operator](/en-US/docs/Web/JavaScript/Reference/Operators#assignment_operators). **Defaults to `false`.**
An **accessor descriptor** also has the following optional keys:
- `get`
- : A function which serves as a getter for the property, or {{jsxref("undefined")}} if there is no getter. When the property is accessed, this function is called without arguments and with `this` set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property. **Defaults to {{jsxref("undefined")}}.**
- `set`
- : A function which serves as a setter for the property, or {{jsxref("undefined")}} if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with `this` set to the object through which the property is assigned. **Defaults to {{jsxref("undefined")}}.**
If a descriptor doesn't have any of the `value`, `writable`, `get`, and `set` keys, it is treated as a data descriptor. If a descriptor has both \[`value` or `writable`] and \[`get` or `set`] keys, an exception is thrown.
These attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or create a [`null`-prototype object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects).
```js
const obj = {};
// 1. Using a null prototype: no inherited properties
const descriptor = Object.create(null);
descriptor.value = "static";
// not enumerable, not configurable, not writable as defaults
Object.defineProperty(obj, "key", descriptor);
// 2. Being explicit by using a throw-away object literal with all attributes present
Object.defineProperty(obj, "key2", {
enumerable: false,
configurable: false,
writable: false,
value: "static",
});
// 3. Recycling same object
function withValue(value) {
const d =
withValue.d ||
(withValue.d = {
enumerable: false,
writable: false,
configurable: false,
value,
});
// avoiding duplicate operation for assigning value
if (d.value !== value) d.value = value;
return d;
}
// and
Object.defineProperty(obj, "key", withValue("static"));
// if freeze is available, prevents adding or
// removing the object prototype properties
// (value, get, set, enumerable, writable, configurable)
(Object.freeze || Object)(Object.prototype);
```
When the property already exists, `Object.defineProperty()` attempts to modify the property according to the values in the descriptor and the property's current configuration.
If the old descriptor had its `configurable` attribute set to `false`, the property is said to be _non-configurable_. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with `writable: true`, it is possible to modify the value and change the `writable` attribute from `true` to `false`. A {{jsxref("TypeError")}} is thrown when attempts are made to change non-configurable property attributes (except `value` and `writable`, if permitted), except when defining a value same as the original value on a data property.
When the current property is configurable, defining an attribute to `undefined` effectively deletes it. For example, if `o.k` is an accessor property, `Object.defineProperty(o, "k", { set: undefined })` will remove the setter, making `k` only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to `undefined`). It is possible to toggle between data and accessor property by giving a descriptor of a different "flavor". For example, if the new descriptor is a data descriptor (with `value` or `writable`), the original descriptor's `get` and `set` attributes will both be dropped.
## Examples
### Creating a property
When the property specified doesn't exist in the object, `Object.defineProperty()` creates a new property as described. Fields may be omitted from the descriptor and default values for those fields are inputted.
```js
const o = {}; // Creates a new object
// Example of an object property added
// with defineProperty with a data property descriptor
Object.defineProperty(o, "a", {
value: 37,
writable: true,
enumerable: true,
configurable: true,
});
// 'a' property exists in the o object and its value is 37
// Example of an object property added
// with defineProperty with an accessor property descriptor
let bValue = 38;
Object.defineProperty(o, "b", {
get() {
return bValue;
},
set(newValue) {
bValue = newValue;
},
enumerable: true,
configurable: true,
});
o.b; // 38
// 'b' property exists in the o object and its value is 38
// The value of o.b is now always identical to bValue,
// unless o.b is redefined
// You cannot try to mix both:
Object.defineProperty(o, "conflict", {
value: 0x9f91102,
get() {
return 0xdeadbeef;
},
});
// throws a TypeError: value appears
// only in data descriptors,
// get appears only in accessor descriptors
```
### Modifying a property
When modifying an existing property, the current property configuration determines if the operator succeeds, does nothing, or throws a {{jsxref("TypeError")}}.
#### Writable attribute
When the `writable` property attribute is `false`, the property is said to be "non-writable". It cannot be reassigned. Trying to write to a non-writable property doesn't change it and results in an error in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode).
```js
const o = {}; // Creates a new object
Object.defineProperty(o, "a", {
value: 37,
writable: false,
});
console.log(o.a); // 37
o.a = 25; // No error thrown
// (it would throw in strict mode,
// even if the value had been the same)
console.log(o.a); // 37; the assignment didn't work
// strict mode
(() => {
"use strict";
const o = {};
Object.defineProperty(o, "b", {
value: 2,
writable: false,
});
o.b = 3; // throws TypeError: "b" is read-only
return o.b; // returns 2 without the line above
})();
```
#### Enumerable attribute
The `enumerable` property attribute defines whether the property is considered by {{jsxref("Object.assign()")}} or the [spread](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) operator. For non-{{jsxref("Symbol")}} properties, it also defines whether it shows up in a {{jsxref("Statements/for...in", "for...in")}} loop and {{jsxref("Object.keys()")}} or not. For more information, see [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties).
```js
const o = {};
Object.defineProperty(o, "a", {
value: 1,
enumerable: true,
});
Object.defineProperty(o, "b", {
value: 2,
enumerable: false,
});
Object.defineProperty(o, "c", {
value: 3,
}); // enumerable defaults to false
o.d = 4; // enumerable defaults to true when creating a property by setting it
Object.defineProperty(o, Symbol.for("e"), {
value: 5,
enumerable: true,
});
Object.defineProperty(o, Symbol.for("f"), {
value: 6,
enumerable: false,
});
for (const i in o) {
console.log(i);
}
// Logs 'a' and 'd' (always in that order)
Object.keys(o); // ['a', 'd']
o.propertyIsEnumerable("a"); // true
o.propertyIsEnumerable("b"); // false
o.propertyIsEnumerable("c"); // false
o.propertyIsEnumerable("d"); // true
o.propertyIsEnumerable(Symbol.for("e")); // true
o.propertyIsEnumerable(Symbol.for("f")); // false
const p = { ...o };
p.a; // 1
p.b; // undefined
p.c; // undefined
p.d; // 4
p[Symbol.for("e")]; // 5
p[Symbol.for("f")]; // undefined
```
#### Configurable attribute
The `configurable` attribute controls whether the property can be deleted from the object and whether its attributes (other than `value` and `writable`) can be changed.
This example illustrates a non-configurable accessor property.
```js
const o = {};
Object.defineProperty(o, "a", {
get() {
return 1;
},
configurable: false,
});
Object.defineProperty(o, "a", {
configurable: true,
}); // throws a TypeError
Object.defineProperty(o, "a", {
enumerable: true,
}); // throws a TypeError
Object.defineProperty(o, "a", {
set() {},
}); // throws a TypeError (set was undefined previously)
Object.defineProperty(o, "a", {
get() {
return 1;
},
}); // throws a TypeError
// (even though the new get does exactly the same thing)
Object.defineProperty(o, "a", {
value: 12,
}); // throws a TypeError
// ('value' can be changed when 'configurable' is false, but only when the property is a writable data property)
console.log(o.a); // 1
delete o.a; // Nothing happens; throws an error in strict mode
console.log(o.a); // 1
```
If the `configurable` attribute of `o.a` had been `true`, none of the errors would be thrown and the property would be deleted at the end.
This example illustrates a non-configurable but writable data property. The property's `value` can still be changed, and `writable` can still be toggled from `true` to `false`.
```js
const o = {};
Object.defineProperty(o, "b", {
writable: true,
configurable: false,
});
console.log(o.b); // undefined
Object.defineProperty(o, "b", {
value: 1,
}); // Even when configurable is false, because the object is writable, we may still replace the value
console.log(o.b); // 1
o.b = 2; // We can change the value with assignment operators as well
console.log(o.b); // 2
// Toggle the property's writability
Object.defineProperty(o, "b", {
writable: false,
});
Object.defineProperty(o, "b", {
value: 1,
}); // TypeError: because the property is neither writable nor configurable, it cannot be modified
// At this point, there's no way to further modify 'b'
// or restore its writability
```
This example illustrates a configurable but non-writable data property. The property's `value` may still be replaced with `defineProperty` (but not with assignment operators), and `writable` may be toggled.
```js
const o = {};
Object.defineProperty(o, "b", {
writable: false,
configurable: true,
});
Object.defineProperty(o, "b", {
value: 1,
}); // We can replace the value with defineProperty
console.log(o.b); // 1
o.b = 2; // throws TypeError in strict mode: cannot change a non-writable property's value with assignment
```
This example illustrates a non-configurable and non-writable data property. There's no way to update any attribute of the property, including its `value`.
```js
const o = {};
Object.defineProperty(o, "b", {
writable: false,
configurable: false,
});
Object.defineProperty(o, "b", {
value: 1,
}); // TypeError: the property cannot be modified because it is neither writable nor configurable.
```
### Adding properties and default values
It is important to consider the way default values of attributes are applied. There is often a difference between using [property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) to assign a value and using `Object.defineProperty()`, as shown in the example below.
```js
const o = {};
o.a = 1;
// is equivalent to:
Object.defineProperty(o, "a", {
value: 1,
writable: true,
configurable: true,
enumerable: true,
});
// On the other hand,
Object.defineProperty(o, "a", { value: 1 });
// is equivalent to:
Object.defineProperty(o, "a", {
value: 1,
writable: false,
configurable: false,
enumerable: false,
});
```
### Custom setters and getters
The example below shows how to implement a self-archiving object. When `temperature` property is set, the `archive` array gets a log entry.
```js
function Archiver() {
let temperature = null;
const archive = [];
Object.defineProperty(this, "temperature", {
get() {
console.log("get!");
return temperature;
},
set(value) {
temperature = value;
archive.push({ val: temperature });
},
});
this.getArchive = () => archive;
}
const arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
arc.getArchive(); // [{ val: 11 }, { val: 13 }]
```
In this example, a getter always returns the same value.
```js
const pattern = {
get() {
return "I always return this string, whatever you have assigned";
},
set() {
this.myname = "this is my name string";
},
};
function TestDefineSetAndGet() {
Object.defineProperty(this, "myproperty", pattern);
}
const instance = new TestDefineSetAndGet();
instance.myproperty = "test";
console.log(instance.myproperty);
// I always return this string, whatever you have assigned
console.log(instance.myname); // this is my name string
```
### Inheritance of properties
If an accessor property is inherited, its `get` and `set` methods will be called when the property is accessed and modified on descendant objects. If these methods use a variable to store the value, this value will be shared by all objects.
```js
function MyClass() {}
let value;
Object.defineProperty(MyClass.prototype, "x", {
get() {
return value;
},
set(x) {
value = x;
},
});
const a = new MyClass();
const b = new MyClass();
a.x = 1;
console.log(b.x); // 1
```
This can be fixed by storing the value in another property. In `get` and `set` methods, `this` points to the object which is used to access or modify the property.
```js
function MyClass() {}
Object.defineProperty(MyClass.prototype, "x", {
get() {
return this.storedX;
},
set(x) {
this.storedX = x;
},
});
const a = new MyClass();
const b = new MyClass();
a.x = 1;
console.log(b.x); // undefined
```
Unlike accessor properties, data properties are always set on the object itself, not on a prototype. However, if a non-writable data property is inherited, it is still prevented from being modified on the object.
```js
function MyClass() {}
MyClass.prototype.x = 1;
Object.defineProperty(MyClass.prototype, "y", {
writable: false,
value: 1,
});
const a = new MyClass();
a.x = 2;
console.log(a.x); // 2
console.log(MyClass.prototype.x); // 1
a.y = 2; // Ignored, throws in strict mode
console.log(a.y); // 1
console.log(MyClass.prototype.y); // 1
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
- {{jsxref("Object.defineProperties()")}}
- {{jsxref("Object.prototype.propertyIsEnumerable()")}}
- {{jsxref("Object.getOwnPropertyDescriptor()")}}
- {{jsxref("Functions/get", "get")}}
- {{jsxref("Functions/set", "set")}}
- {{jsxref("Object.create()")}}
- {{jsxref("Reflect.defineProperty()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/getownpropertynames/index.md | ---
title: Object.getOwnPropertyNames()
slug: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.getOwnPropertyNames
---
{{JSRef}}
The **`Object.getOwnPropertyNames()`** static method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.
{{EmbedInteractiveExample("pages/js/object-getownpropertynames.html")}}
## Syntax
```js-nolint
Object.getOwnPropertyNames(obj)
```
### Parameters
- `obj`
- : The object whose enumerable and non-enumerable properties are to be returned.
### Return value
An array of strings that corresponds to the properties found directly in the given object.
## Description
`Object.getOwnPropertyNames()` returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object `obj`. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a {{jsxref("Statements/for...in", "for...in")}} loop (or by {{jsxref("Object.keys()")}}) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion.
In ES5, if the argument to this method is not an object (a primitive), then it will cause a {{jsxref("TypeError")}}. In ES2015, a non-object argument will be coerced to an object.
```js
Object.getOwnPropertyNames("foo");
// TypeError: "foo" is not an object (ES5 code)
Object.getOwnPropertyNames("foo");
// ["0", "1", "2", "length"] (ES2015 code)
```
## Examples
### Using Object.getOwnPropertyNames()
```js
const arr = ["a", "b", "c"];
console.log(Object.getOwnPropertyNames(arr).sort());
// ["0", "1", "2", "length"]
// Array-like object
const obj = { 0: "a", 1: "b", 2: "c" };
console.log(Object.getOwnPropertyNames(obj).sort());
// ["0", "1", "2"]
Object.getOwnPropertyNames(obj).forEach((val, idx, array) => {
console.log(`${val} -> ${obj[val]}`);
});
// 0 -> a
// 1 -> b
// 2 -> c
// non-enumerable property
const myObj = Object.create(
{},
{
getFoo: {
value() {
return this.foo;
},
enumerable: false,
},
},
);
myObj.foo = 1;
console.log(Object.getOwnPropertyNames(myObj).sort()); // ["foo", "getFoo"]
```
If you want only the enumerable properties, see {{jsxref("Object.keys()")}} or use a {{jsxref("Statements/for...in", "for...in")}} loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter is filtered with {{jsxref("Object.hasOwn()")}}).
Items on the prototype chain are not listed:
```js
function ParentClass() {}
ParentClass.prototype.inheritedMethod = function () {};
function ChildClass() {
this.prop = 5;
this.method = function () {};
}
ChildClass.prototype = new ParentClass();
ChildClass.prototype.prototypeMethod = function () {};
console.log(Object.getOwnPropertyNames(new ChildClass()));
// ["prop", "method"]
```
### Get non-enumerable properties only
This uses the {{jsxref("Array.prototype.filter()")}} function to remove the enumerable keys (obtained with {{jsxref("Object.keys()")}}) from a list of all keys (obtained with `Object.getOwnPropertyNames()`) thus giving only the non-enumerable keys as output.
```js
const target = myObject;
const enumAndNonenum = Object.getOwnPropertyNames(target);
const enumOnly = new Set(Object.keys(target));
const nonenumOnly = enumAndNonenum.filter((key) => !enumOnly.has(key));
console.log(nonenumOnly);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.getOwnPropertyNames` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
- {{jsxref("Object.hasOwn()")}}
- {{jsxref("Object.prototype.propertyIsEnumerable()")}}
- {{jsxref("Object.create()")}}
- {{jsxref("Object.keys()")}}
- {{jsxref("Array.prototype.forEach()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/seal/index.md | ---
title: Object.seal()
slug: Web/JavaScript/Reference/Global_Objects/Object/seal
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.seal
---
{{JSRef}}
The **`Object.seal()`** static method _seals_ an object. Sealing an object [prevents extensions](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions) and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. `seal()` returns the same object that was passed in.
{{EmbedInteractiveExample("pages/js/object-seal.html")}}
## Syntax
```js-nolint
Object.seal(obj)
```
### Parameters
- `obj`
- : The object which should be sealed.
### Return value
The object being sealed.
## Description
Sealing an object is equivalent to [preventing extensions](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions) and then changing all existing [properties' descriptors](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description) to `configurable: false`. This has the effect of making the set of properties on the object fixed. Making all properties non-configurable
also prevents them from being converted from data properties to accessor properties and
vice versa, but it does not prevent the values of data properties from being changed.
Attempting to delete or add properties to a sealed object, or to convert a data property
to accessor or vice versa, will fail, either silently or by throwing a
{{jsxref("TypeError")}} (most commonly, although not exclusively, when in
{{jsxref("Strict_mode", "strict mode", "", 1)}} code).
[Private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) do not have the concept of property descriptors. Private properties cannot be added or removed from the object, whether the object is sealed or not.
The prototype chain remains untouched. However, due to the effect of [preventing extensions](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions), the `[[Prototype]]` cannot be reassigned.
Unlike {{jsxref("Object.freeze()")}}, objects sealed with `Object.seal()` may have their existing
properties changed, as long as they are writable.
## Examples
### Using Object.seal
```js
const obj = {
prop() {},
foo: "bar",
};
// New properties may be added, existing properties
// may be changed or removed.
obj.foo = "baz";
obj.lumpy = "woof";
delete obj.prop;
const o = Object.seal(obj);
o === obj; // true
Object.isSealed(obj); // true
// Changing property values on a sealed object
// still works.
obj.foo = "quux";
// But you can't convert data properties to accessors,
// or vice versa.
Object.defineProperty(obj, "foo", {
get() {
return "g";
},
}); // throws a TypeError
// Now any changes, other than to property values,
// will fail.
obj.quaxxor = "the friendly duck";
// silently doesn't add the property
delete obj.foo;
// silently doesn't delete the property
// ...and in strict mode such attempts
// will throw TypeErrors.
function fail() {
"use strict";
delete obj.foo; // throws a TypeError
obj.sparky = "arf"; // throws a TypeError
}
fail();
// Attempted additions through
// Object.defineProperty will also throw.
Object.defineProperty(obj, "ohai", {
value: 17,
}); // throws a TypeError
Object.defineProperty(obj, "foo", {
value: "eit",
}); // changes existing property value
```
### Non-object argument
In ES5, if the argument to this method is not an object (a primitive), then it will cause a {{jsxref("TypeError")}}. In ES2015, a non-object argument will be returned as-is without any errors, since primitives are already, by definition, immutable.
```js
Object.seal(1);
// TypeError: 1 is not an object (ES5 code)
Object.seal(1);
// 1 (ES2015 code)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Object.isSealed()")}}
- {{jsxref("Object.preventExtensions()")}}
- {{jsxref("Object.isExtensible()")}}
- {{jsxref("Object.freeze()")}}
- {{jsxref("Object.isFrozen()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/object | data/mdn-content/files/en-us/web/javascript/reference/global_objects/object/entries/index.md | ---
title: Object.entries()
slug: Web/JavaScript/Reference/Global_Objects/Object/entries
page-type: javascript-static-method
browser-compat: javascript.builtins.Object.entries
---
{{JSRef}}
The **`Object.entries()`** static method returns an array of a given object's own enumerable string-keyed property key-value pairs.
{{EmbedInteractiveExample("pages/js/object-entries.html")}}
## Syntax
```js-nolint
Object.entries(obj)
```
### Parameters
- `obj`
- : An object.
### Return value
An array of the given object's own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value.
## Description
`Object.entries()` returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon `object`. This is the same as iterating with a {{jsxref("Statements/for...in", "for...in")}} loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.entries()` is the same as that provided by a {{jsxref("Statements/for...in", "for...in")}} loop.
If you only need the property keys, use {{jsxref("Object.keys()")}} instead. If you only need the property values, use {{jsxref("Object.values()")}} instead.
## Examples
### Using Object.entries()
```js
const obj = { foo: "bar", baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
const arrayLike = { 0: "a", 1: "b", 2: "c" };
console.log(Object.entries(arrayLike)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]
const randomKeyOrder = { 100: "a", 2: "b", 7: "c" };
console.log(Object.entries(randomKeyOrder)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]
// getFoo is a non-enumerable property
const myObj = Object.create(
{},
{
getFoo: {
value() {
return this.foo;
},
},
},
);
myObj.foo = "bar";
console.log(Object.entries(myObj)); // [ ['foo', 'bar'] ]
```
### Using Object.entries() on primitives
Non-object arguments are [coerced to objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion). [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) and [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) cannot be coerced to objects and throw a {{jsxref("TypeError")}} upfront. Only strings may have own enumerable properties, while all other primitives return an empty array.
```js
// Strings have indices as enumerable own properties
console.log(Object.entries("foo")); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ]
// Other primitives except undefined and null have no own properties
console.log(Object.entries(100)); // []
```
### Converting an Object to a Map
The {{jsxref("Map/Map", "Map()")}} constructor accepts an iterable of `entries`. With `Object.entries`, you can easily convert from {{jsxref("Object")}} to {{jsxref("Map")}}:
```js
const obj = { foo: "bar", baz: 42 };
const map = new Map(Object.entries(obj));
console.log(map); // Map(2) {"foo" => "bar", "baz" => 42}
```
### Iterating through an Object
Using [array destructuring](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#array_destructuring), you can iterate through objects easily.
```js
// Using for...of loop
const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
}
// Using array methods
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Object.entries` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
- {{jsxref("Object.keys()")}}
- {{jsxref("Object.values()")}}
- {{jsxref("Object.prototype.propertyIsEnumerable()")}}
- {{jsxref("Object.create()")}}
- {{jsxref("Object.fromEntries()")}}
- {{jsxref("Object.getOwnPropertyNames()")}}
- {{jsxref("Map.prototype.entries()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/aggregateerror/index.md | ---
title: AggregateError
slug: Web/JavaScript/Reference/Global_Objects/AggregateError
page-type: javascript-class
browser-compat: javascript.builtins.AggregateError
---
{{JSRef}}
The **`AggregateError`** object represents an error when several errors need to be wrapped in a single error. It is thrown when multiple errors need to be reported by an operation, for example by {{jsxref("Promise.any()")}}, when all promises passed to it reject.
`AggregateError` is a subclass of {{jsxref("Error")}}.
## Constructor
- {{jsxref("AggregateError/AggregateError", "AggregateError()")}}
- : Creates a new `AggregateError` object.
## Instance properties
_Also inherits instance properties from its parent {{jsxref("Error")}}_.
These properties are defined on `AggregateError.prototype` and shared by all `AggregateError` instances.
- {{jsxref("Object/constructor", "AggregateError.prototype.constructor")}}
- : The constructor function that created the instance object. For `AggregateError` instances, the initial value is the {{jsxref("AggregateError/AggregateError", "AggregateError")}} constructor.
- {{jsxref("Error/name", "AggregateError.prototype.name")}}
- : Represents the name for the type of error. For `AggregateError.prototype.name`, the initial value is `"AggregateError"`.
These properties are own properties of each `AggregateError` instance.
- {{jsxref("AggregateError/errors", "errors")}}
- : An array representing the errors that were aggregated.
## Instance methods
_Inherits instance methods from its parent {{jsxref("Error")}}_.
## Examples
### Catching an AggregateError
```js
Promise.any([Promise.reject(new Error("some error"))]).catch((e) => {
console.log(e instanceof AggregateError); // true
console.log(e.message); // "All Promises rejected"
console.log(e.name); // "AggregateError"
console.log(e.errors); // [ Error: "some error" ]
});
```
### Creating an AggregateError
```js
try {
throw new AggregateError([new Error("some error")], "Hello");
} catch (e) {
console.log(e instanceof AggregateError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "AggregateError"
console.log(e.errors); // [ Error: "some error" ]
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `AggregateError` in `core-js`](https://github.com/zloirock/core-js#ecmascript-promise)
- {{jsxref("Error")}}
- {{jsxref("Promise.any")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/aggregateerror | data/mdn-content/files/en-us/web/javascript/reference/global_objects/aggregateerror/errors/index.md | ---
title: "AggregateError: errors"
slug: Web/JavaScript/Reference/Global_Objects/AggregateError/errors
page-type: javascript-instance-data-property
browser-compat: javascript.builtins.AggregateError.errors
---
{{JSRef}}
The **`errors`** data property of an {{jsxref("AggregateError")}} instance contains an array representing the errors that were aggregated.
## Value
An {{jsxref("Array")}} containing values in the same order as the iterable passed as the first argument of the {{jsxref("AggregateError/AggregateError", "AggregateError()")}} constructor.
{{js_property_attributes(1, 0, 1)}}
## Examples
### Using errors
```js
try {
throw new AggregateError(
// An iterable of errors
new Set([new Error("some error"), new Error("another error")]),
"Multiple errors thrown",
);
} catch (err) {
console.log(err.errors);
// [
// Error: some error,
// Error: another error
// ]
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Control flow and error handling](/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling) guide
- {{jsxref("AggregateError")}}
- [`Error`: `cause`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/aggregateerror | data/mdn-content/files/en-us/web/javascript/reference/global_objects/aggregateerror/aggregateerror/index.md | ---
title: AggregateError() constructor
slug: Web/JavaScript/Reference/Global_Objects/AggregateError/AggregateError
page-type: javascript-constructor
browser-compat: javascript.builtins.AggregateError.AggregateError
---
{{JSRef}}
The **`AggregateError()`** constructor creates {{jsxref("AggregateError")}} objects.
## Syntax
```js-nolint
new AggregateError(errors)
new AggregateError(errors, message)
new AggregateError(errors, message, options)
AggregateError(errors)
AggregateError(errors, message)
AggregateError(errors, message, options)
```
> **Note:** `AggregateError()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `AggregateError` instance.
### Parameters
- `errors`
- : An iterable of errors, may not actually be {{jsxref("Error")}} instances.
- `message` {{optional_inline}}
- : An optional human-readable description of the aggregate error.
- `options` {{optional_inline}}
- : An object that has the following properties:
- `cause` {{optional_inline}}
- : A property indicating the specific cause of the error.
When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.
## Examples
### Creating an AggregateError
```js
try {
throw new AggregateError([new Error("some error")], "Hello");
} catch (e) {
console.log(e instanceof AggregateError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "AggregateError"
console.log(e.errors); // [ Error: "some error" ]
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `AggregateError` in `core-js`](https://github.com/zloirock/core-js#ecmascript-promise)
- {{jsxref("Promise.any")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/asyncfunction/index.md | ---
title: AsyncFunction
slug: Web/JavaScript/Reference/Global_Objects/AsyncFunction
page-type: javascript-class
browser-compat: javascript.builtins.AsyncFunction
---
{{JSRef}}
The **`AsyncFunction`** object provides methods for [async functions](/en-US/docs/Web/JavaScript/Reference/Statements/async_function). In JavaScript, every async function is actually an `AsyncFunction` object.
Note that `AsyncFunction` is _not_ a global object. It can be obtained with the following code:
```js
const AsyncFunction = async function () {}.constructor;
```
`AsyncFunction` is a subclass of {{jsxref("Function")}}.
## Constructor
- {{jsxref("AsyncFunction/AsyncFunction", "AsyncFunction()")}}
- : Creates a new `AsyncFunction` object.
## Instance properties
_Also inherits instance properties from its parent {{jsxref("Function")}}_.
These properties are defined on `AsyncFunction.prototype` and shared by all `AsyncFunction` instances.
- {{jsxref("Object/constructor", "AsyncFunction.prototype.constructor")}}
- : The constructor function that created the instance object. For `AsyncFunction` instances, the initial value is the {{jsxref("AsyncFunction/AsyncFunction", "AsyncFunction")}} constructor.
- `AsyncFunction.prototype[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"AsyncFunction"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
> **Note:** `AsyncFunction` instances do not have the [`prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype) property.
## Instance methods
_Inherits instance methods from its parent {{jsxref("Function")}}_.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`async function`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
- [`async function` expression](/en-US/docs/Web/JavaScript/Reference/Operators/async_function)
- {{jsxref("Function")}}
- {{jsxref("AsyncGeneratorFunction")}}
- {{jsxref("GeneratorFunction")}}
- {{jsxref("Functions", "Functions", "", 1)}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/asyncfunction | data/mdn-content/files/en-us/web/javascript/reference/global_objects/asyncfunction/asyncfunction/index.md | ---
title: AsyncFunction() constructor
slug: Web/JavaScript/Reference/Global_Objects/AsyncFunction/AsyncFunction
page-type: javascript-constructor
browser-compat: javascript.builtins.AsyncFunction.AsyncFunction
---
{{JSRef}}
The **`AsyncFunction()`** constructor creates {{jsxref("AsyncFunction")}} objects.
Note that `AsyncFunction` is _not_ a global object. It can be obtained with the following code:
```js
const AsyncFunction = async function () {}.constructor;
```
The `AsyncFunction()` constructor is not intended to be used directly, and all caveats mentioned in the {{jsxref("Function/Function", "Function()")}} description apply to `AsyncFunction()`.
## Syntax
```js-nolint
new AsyncFunction(functionBody)
new AsyncFunction(arg1, functionBody)
new AsyncFunction(arg1, arg2, functionBody)
new AsyncFunction(arg1, arg2, /* …, */ argN, functionBody)
AsyncFunction(functionBody)
AsyncFunction(arg1, functionBody)
AsyncFunction(arg1, arg2, functionBody)
AsyncFunction(arg1, arg2, /* …, */ argN, functionBody)
```
> **Note:** `AsyncFunction()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `AsyncFunction` instance.
### Parameters
See {{jsxref("Function/Function", "Function()")}}.
## Examples
### Creating an async function from an AsyncFunction() constructor
```js
function resolveAfter2Seconds(x) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
const AsyncFunction = async function () {}.constructor;
const fn = new AsyncFunction(
"a",
"b",
"return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);",
);
fn(10, 20).then((v) => {
console.log(v); // prints 30 after 4 seconds
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`async function`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
- [`async function` expression](/en-US/docs/Web/JavaScript/Reference/Operators/async_function)
- [`Function()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/index.md | ---
title: String
slug: Web/JavaScript/Reference/Global_Objects/String
page-type: javascript-class
browser-compat: javascript.builtins.String
---
{{JSRef}}
The **`String`** object is used to represent and manipulate a
sequence of characters.
## Description
Strings are useful for holding data that can be represented in text form. Some of the
most-used operations on strings are to check their {{jsxref("String/length", "length")}}, to build and concatenate them using the
[`+` and `+=` string operators](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#string_operators),
checking for the existence or location of substrings with the
{{jsxref("String/indexOf", "indexOf()")}} method, or extracting substrings
with the {{jsxref("String/substring", "substring()")}} method.
### Creating strings
Strings can be created as primitives, from string literals, or as objects, using the
{{jsxref("String/String", "String()")}} constructor:
```js-nolint
const string1 = "A string primitive";
const string2 = 'Also a string primitive';
const string3 = `Yet another string primitive`;
```
```js
const string4 = new String("A String object");
```
String primitives and string objects share many behaviors, but have other important differences and caveats.
See "[String primitives and String objects](#string_primitives_and_string_objects)" below.
String literals can be specified using single or double quotes, which are treated
identically, or using the backtick character <kbd>`</kbd>. This last form specifies a [template literal](/en-US/docs/Web/JavaScript/Reference/Template_literals):
with this form you can interpolate expressions. For more information on the syntax of string literals, see [lexical grammar](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#string_literals).
### Character access
There are two ways to access an individual character in a string. The first is the
{{jsxref("String/charAt", "charAt()")}} method:
```js
"cat".charAt(1); // gives value "a"
```
The other way is to treat the string as an array-like object, where individual characters correspond to a numerical index:
```js
"cat"[1]; // gives value "a"
```
When using bracket notation for character access, attempting to delete or assign a
value to these properties will not succeed. The properties involved are neither writable
nor configurable. (See {{jsxref("Object.defineProperty()")}} for more information.)
### Comparing strings
Use the [less-than and greater-than operators](/en-US/docs/Web/JavaScript/Reference/Operators) to compare strings:
```js
const a = "a";
const b = "b";
if (a < b) {
// true
console.log(`${a} is less than ${b}`);
} else if (a > b) {
console.log(`${a} is greater than ${b}`);
} else {
console.log(`${a} and ${b} are equal.`);
}
```
Note that all comparison operators, including [`===`](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) and [`==`](/en-US/docs/Web/JavaScript/Reference/Operators/Equality), compare strings case-sensitively. A common way to compare strings case-insensitively is to convert both to the same case (upper or lower) before comparing them.
```js
function areEqualCaseInsensitive(str1, str2) {
return str1.toUpperCase() === str2.toUpperCase();
}
```
The choice of whether to transform by [`toUpperCase()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) or [`toLowerCase()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) is mostly arbitrary, and neither one is fully robust when extending beyond the Latin alphabet. For example, the German lowercase letter `ß` and `ss` are both transformed to `SS` by `toUpperCase()`, while the Turkish letter `ı` would be falsely reported as unequal to `I` by `toLowerCase()` unless specifically using [`toLocaleLowerCase("tr")`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase).
```js
const areEqualInUpperCase = (str1, str2) =>
str1.toUpperCase() === str2.toUpperCase();
const areEqualInLowerCase = (str1, str2) =>
str1.toLowerCase() === str2.toLowerCase();
areEqualInUpperCase("ß", "ss"); // true; should be false
areEqualInLowerCase("ı", "I"); // false; should be true
```
A locale-aware and robust solution for testing case-insensitive equality is to use the {{jsxref("Intl.Collator")}} API or the string's [`localeCompare()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare) method — they share the same interface — with the [`sensitivity`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#sensitivity) option set to `"accent"` or `"base"`.
```js
const areEqual = (str1, str2, locale = "en-US") =>
str1.localeCompare(str2, locale, { sensitivity: "accent" }) === 0;
areEqual("ß", "ss", "de"); // false
areEqual("ı", "I", "tr"); // true
```
The `localeCompare()` method enables string comparison in a similar fashion as `strcmp()` — it allows sorting strings in a locale-aware manner.
### String primitives and String objects
Note that JavaScript distinguishes between `String` objects and
{{Glossary("Primitive", "primitive string")}} values. (The same is true of
{{jsxref("Boolean")}} and {{jsxref("Number", "Numbers")}}.)
String literals (denoted by double or single quotes) and strings returned from
`String` calls in a non-constructor context (that is, called without using
the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. In contexts where a
method is to be invoked on a primitive string or a property lookup occurs, JavaScript
will automatically wrap the string primitive and call the method or perform the property
lookup on the wrapper object instead.
```js
const strPrim = "foo"; // A literal is a string primitive
const strPrim2 = String(1); // Coerced into the string primitive "1"
const strPrim3 = String(true); // Coerced into the string primitive "true"
const strObj = new String(strPrim); // String with new returns a string wrapper object.
console.log(typeof strPrim); // "string"
console.log(typeof strPrim2); // "string"
console.log(typeof strPrim3); // "string"
console.log(typeof strObj); // "object"
```
> **Warning:** You should rarely find yourself using `String` as a constructor.
String primitives and `String` objects also give different results when
using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to
`eval` are treated as source code; `String` objects are treated as
all other objects are, by returning the object. For example:
```js
const s1 = "2 + 2"; // creates a string primitive
const s2 = new String("2 + 2"); // creates a String object
console.log(eval(s1)); // returns the number 4
console.log(eval(s2)); // returns the string "2 + 2"
```
For these reasons, the code may break when it encounters `String` objects
when it expects a primitive string instead, although generally, authors need not worry
about the distinction.
A `String` object can always be converted to its primitive counterpart with
the {{jsxref("String/valueOf", "valueOf()")}} method.
```js
console.log(eval(s2.valueOf())); // returns the number 4
```
### String coercion
Many built-in operations that expect strings first coerce their arguments to strings (which is largely why `String` objects behave similarly to string primitives). [The operation](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-tostring) can be summarized as follows:
- Strings are returned as-is.
- [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) turns into `"undefined"`.
- [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) turns into `"null"`.
- `true` turns into `"true"`; `false` turns into `"false"`.
- Numbers are converted with the same algorithm as [`toString(10)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString).
- [BigInts](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) are converted with the same algorithm as [`toString(10)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/toString).
- [Symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) throw a {{jsxref("TypeError")}}.
- Objects are first [converted to a primitive](/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive) (with `"string"` as hint), `toString()`, and `valueOf()` methods, in that order. The resulting primitive is then converted to a string.
There are several ways to achieve nearly the same effect in JavaScript.
- [Template literal](/en-US/docs/Web/JavaScript/Reference/Template_literals): `` `${x}` `` does exactly the string coercion steps explained above for the embedded expression.
- The [`String()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/String) function: `String(x)` uses the same algorithm to convert `x`, except that [Symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) don't throw a {{jsxref("TypeError")}}, but return `"Symbol(description)"`, where `description` is the [description](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/description) of the Symbol.
- Using the [`+` operator](/en-US/docs/Web/JavaScript/Reference/Operators/Addition): `"" + x` coerces its operand to a _primitive_ instead of a _string_, and, for some objects, has entirely different behaviors from normal string coercion. See its [reference page](/en-US/docs/Web/JavaScript/Reference/Operators/Addition) for more details.
Depending on your use case, you may want to use `` `${x}` `` (to mimic built-in behavior) or `String(x)` (to handle symbol values without throwing an error), but you should not use `"" + x`.
### UTF-16 characters, Unicode code points, and grapheme clusters
Strings are represented fundamentally as sequences of [UTF-16 code units](https://en.wikipedia.org/wiki/UTF-16). In UTF-16 encoding, every code unit is exact 16 bits long. This means there are a maximum of 2<sup>16</sup>, or 65536 possible characters representable as single UTF-16 code units. This character set is called the [basic multilingual plane (BMP)](<https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane>), and includes the most common characters like the Latin, Greek, Cyrillic alphabets, as well as many East Asian characters. Each code unit can be written in a string with `\u` followed by exactly four hex digits.
However, the entire Unicode character set is much, much bigger than 65536. The extra characters are stored in UTF-16 as _surrogate pairs_, which are pairs of 16-bit code units that represent a single character. To avoid ambiguity, the two parts of the pair must be between `0xD800` and `0xDFFF`, and these code units are not used to encode single-code-unit characters. (More precisely, leading surrogates, also called high-surrogate code units, have values between `0xD800` and `0xDBFF`, inclusive, while trailing surrogates, also called low-surrogate code units, have values between `0xDC00` and `0xDFFF`, inclusive.) Each Unicode character, comprised of one or two UTF-16 code units, is also called a _Unicode code point_. Each Unicode code point can be written in a string with `\u{xxxxxx}` where `xxxxxx` represents 1–6 hex digits.
A "lone surrogate" is a 16-bit code unit satisfying one of the descriptions below:
- It is in the range `0xD800`–`0xDBFF`, inclusive (i.e. is a leading surrogate), but it is the last code unit in the string, or the next code unit is not a trailing surrogate.
- It is in the range `0xDC00`–`0xDFFF`, inclusive (i.e. is a trailing surrogate), but it is the first code unit in the string, or the previous code unit is not a leading surrogate.
Lone surrogates do not represent any Unicode character. Although most JavaScript built-in methods handle them correctly because they all work based on UTF-16 code units, lone surrogates are often not valid values when interacting with other systems — for example, [`encodeURI()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) will throw a {{jsxref("URIError")}} for lone surrogates, because URI encoding uses UTF-8 encoding, which does not have any encoding for lone surrogates. Strings not containing any lone surrogates are called _well-formed_ strings, and are safe to be used with functions that do not deal with UTF-16 (such as `encodeURI()` or {{domxref("TextEncoder")}}). You can check if a string is well-formed with the {{jsxref("String/isWellFormed", "isWellFormed()")}} method, or sanitize lone surrogates with the {{jsxref("String/toWellFormed", "toWellFormed()")}} method.
On top of Unicode characters, there are certain sequences of Unicode characters that should be treated as one visual unit, known as a _grapheme cluster_. The most common case is emojis: many emojis that have a range of variations are actually formed by multiple emojis, usually joined by the \<ZWJ> (`U+200D`) character.
You must be careful which level of characters you are iterating on. For example, [`split("")`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) will split by UTF-16 code units and will separate surrogate pairs. String indexes also refer to the index of each UTF-16 code unit. On the other hand, [`@@iterator()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@iterator) iterates by Unicode code points. Iterating through grapheme clusters will require some custom code.
```js
"😄".split(""); // ['\ud83d', '\ude04']; splits into two lone surrogates
// "Backhand Index Pointing Right: Dark Skin Tone"
[..."👉🏿"]; // ['👉', '🏿']
// splits into the basic "Backhand Index Pointing Right" emoji and
// the "Dark skin tone" emoji
// "Family: Man, Boy"
[..."👨👦"]; // [ '👨', '', '👦' ]
// splits into the "Man" and "Boy" emoji, joined by a ZWJ
// The United Nations flag
[..."🇺🇳"]; // [ '🇺', '🇳' ]
// splits into two "region indicator" letters "U" and "N".
// All flag emojis are formed by joining two region indicator letters
```
## Constructor
- {{jsxref("String/String", "String()")}}
- : Creates a new `String` object. It performs type conversion when called as
a function, rather than as a constructor, which is usually more useful.
## Static methods
- {{jsxref("String.fromCharCode()")}}
- : Returns a string created by using the specified sequence of Unicode values.
- {{jsxref("String.fromCodePoint()")}}
- : Returns a string created by using the specified sequence of code points.
- {{jsxref("String.raw()")}}
- : Returns a string created from a raw template string.
## Instance properties
These properties are defined on `String.prototype` and shared by all `String` instances.
- {{jsxref("Object/constructor", "String.prototype.constructor")}}
- : The constructor function that created the instance object. For `String` instances, the initial value is the {{jsxref("String/String", "String")}} constructor.
These properties are own properties of each `String` instance.
- {{jsxref("String/length", "length")}}
- : Reflects the `length` of the string. Read-only.
## Instance methods
- {{jsxref("String.prototype.at()")}}
- : Returns the character (exactly one UTF-16 code unit) at the specified `index`. Accepts negative integers, which count back from the last string character.
- {{jsxref("String.prototype.charAt()")}}
- : Returns the character (exactly one UTF-16 code unit) at the specified
`index`.
- {{jsxref("String.prototype.charCodeAt()")}}
- : Returns a number that is the UTF-16 code unit value at the given
`index`.
- {{jsxref("String.prototype.codePointAt()")}}
- : Returns a nonnegative integer Number that is the code point value of the UTF-16
encoded code point starting at the specified `pos`.
- {{jsxref("String.prototype.concat()")}}
- : Combines the text of two (or more) strings and returns a new string.
- {{jsxref("String.prototype.endsWith()")}}
- : Determines whether a string ends with the characters of the string
`searchString`.
- {{jsxref("String.prototype.includes()")}}
- : Determines whether the calling string contains `searchString`.
- {{jsxref("String.prototype.indexOf()")}}
- : Returns the index within the calling {{jsxref("String")}} object of the first
occurrence of `searchValue`, or `-1` if not found.
- {{jsxref("String.prototype.isWellFormed()")}}
- : Returns a boolean indicating whether this string contains any [lone surrogates](#utf-16_characters_unicode_code_points_and_grapheme_clusters).
- {{jsxref("String.prototype.lastIndexOf()")}}
- : Returns the index within the calling {{jsxref("String")}} object of the last
occurrence of `searchValue`, or `-1` if not found.
- {{jsxref("String.prototype.localeCompare()")}}
- : Returns a number indicating whether the reference string
`compareString` comes before, after, or is equivalent to the
given string in sort order.
- {{jsxref("String.prototype.match()")}}
- : Used to match regular expression `regexp` against a string.
- {{jsxref("String.prototype.matchAll()")}}
- : Returns an iterator of all `regexp`'s matches.
- {{jsxref("String.prototype.normalize()")}}
- : Returns the Unicode Normalization Form of the calling string value.
- {{jsxref("String.prototype.padEnd()")}}
- : Pads the current string from the end with a given string and returns a new string of
the length `targetLength`.
- {{jsxref("String.prototype.padStart()")}}
- : Pads the current string from the start with a given string and returns a new string
of the length `targetLength`.
- {{jsxref("String.prototype.repeat()")}}
- : Returns a string consisting of the elements of the object repeated
`count` times.
- {{jsxref("String.prototype.replace()")}}
- : Used to replace occurrences of `searchFor` using
`replaceWith`. `searchFor` may be a string
or Regular Expression, and `replaceWith` may be a string or
function.
- {{jsxref("String.prototype.replaceAll()")}}
- : Used to replace all occurrences of `searchFor` using
`replaceWith`. `searchFor` may be a string
or Regular Expression, and `replaceWith` may be a string or
function.
- {{jsxref("String.prototype.search()")}}
- : Search for a match between a regular expression `regexp` and
the calling string.
- {{jsxref("String.prototype.slice()")}}
- : Extracts a section of a string and returns a new string.
- {{jsxref("String.prototype.split()")}}
- : Returns an array of strings populated by splitting the calling string at occurrences
of the substring `sep`.
- {{jsxref("String.prototype.startsWith()")}}
- : Determines whether the calling string begins with the characters of string
`searchString`.
- {{jsxref("String.prototype.substr()")}} {{deprecated_inline}}
- : Returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards.
- {{jsxref("String.prototype.substring()")}}
- : Returns a new string containing characters of the calling string from (or between)
the specified index (or indices).
- {{jsxref("String.prototype.toLocaleLowerCase()")}}
- : The characters within a string are converted to lowercase while respecting the
current locale.
For most languages, this will return the same as
{{jsxref("String/toLowerCase", "toLowerCase()")}}.
- {{jsxref("String.prototype.toLocaleUpperCase()")}}
- : The characters within a string are converted to uppercase while respecting the
current locale.
For most languages, this will return the same as
{{jsxref("String/toUpperCase", "toUpperCase()")}}.
- {{jsxref("String.prototype.toLowerCase()")}}
- : Returns the calling string value converted to lowercase.
- {{jsxref("String.prototype.toString()")}}
- : Returns a string representing the specified object. Overrides the
{{jsxref("Object.prototype.toString()")}} method.
- {{jsxref("String.prototype.toUpperCase()")}}
- : Returns the calling string value converted to uppercase.
- {{jsxref("String.prototype.toWellFormed()")}}
- : Returns a string where all [lone surrogates](#utf-16_characters_unicode_code_points_and_grapheme_clusters) of this string are replaced with the Unicode replacement character U+FFFD.
- {{jsxref("String.prototype.trim()")}}
- : Trims whitespace from the beginning and end of the string.
- {{jsxref("String.prototype.trimEnd()")}}
- : Trims whitespace from the end of the string.
- {{jsxref("String.prototype.trimStart()")}}
- : Trims whitespace from the beginning of the string.
- {{jsxref("String.prototype.valueOf()")}}
- : Returns the primitive value of the specified object. Overrides the
{{jsxref("Object.prototype.valueOf()")}} method.
- [`String.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@iterator)
- : Returns a new iterator object that iterates over the code points of a String value,
returning each code point as a String value.
### HTML wrapper methods
> **Warning:** Deprecated. Avoid these methods.
>
> They are of limited use, as they are based on a very old HTML standard and provide only a subset of the currently available HTML tags and attributes. Many of them create deprecated or non-standard markup today. In addition, they do simple string concatenation without any validation or sanitation, which makes them a potential security threat when directly inserted using [`innerHTML`](/en-US/docs/Web/API/Element/innerHTML). Use [DOM APIs](/en-US/docs/Web/API/Document_Object_Model) such as [`document.createElement()`](/en-US/docs/Web/API/Document/createElement) instead.
- {{jsxref("String.prototype.anchor()")}} {{deprecated_inline}}
- : [`<a name="name">`](/en-US/docs/Web/HTML/Element/a#name) (hypertext target)
- {{jsxref("String.prototype.big()")}} {{deprecated_inline}}
- : {{HTMLElement("big")}}
- {{jsxref("String.prototype.blink()")}} {{deprecated_inline}}
- : `<blink>`
- {{jsxref("String.prototype.bold()")}} {{deprecated_inline}}
- : {{HTMLElement("b")}}
- {{jsxref("String.prototype.fixed()")}} {{deprecated_inline}}
- : {{HTMLElement("tt")}}
- {{jsxref("String.prototype.fontcolor()")}} {{deprecated_inline}}
- : [`<font color="color">`](/en-US/docs/Web/HTML/Element/font#color)
- {{jsxref("String.prototype.fontsize()")}} {{deprecated_inline}}
- : [`<font size="size">`](/en-US/docs/Web/HTML/Element/font#size)
- {{jsxref("String.prototype.italics()")}} {{deprecated_inline}}
- : {{HTMLElement("i")}}
- {{jsxref("String.prototype.link()")}} {{deprecated_inline}}
- : [`<a href="url">`](/en-US/docs/Web/HTML/Element/a#href) (link to URL)
- {{jsxref("String.prototype.small()")}} {{deprecated_inline}}
- : {{HTMLElement("small")}}
- {{jsxref("String.prototype.strike()")}} {{deprecated_inline}}
- : {{HTMLElement("strike")}}
- {{jsxref("String.prototype.sub()")}} {{deprecated_inline}}
- : {{HTMLElement("sub")}}
- {{jsxref("String.prototype.sup()")}} {{deprecated_inline}}
- : {{HTMLElement("sup")}}
Note that these methods do not check if the string itself contains HTML tags, so it's possible to create invalid HTML:
```js
"</b>".bold(); // <b></b></b>
```
The only escaping they do is to replace `"` in the attribute value (for {{jsxref("String/anchor", "anchor()")}}, {{jsxref("String/fontcolor", "fontcolor()")}}, {{jsxref("String/fontsize", "fontsize()")}}, and {{jsxref("String/link", "link()")}}) with `"`.
```js
"foo".anchor('"Hello"'); // <a name=""Hello"">foo</a>
```
## Examples
### String conversion
The `String()` function is a more reliable way of converting values to strings than calling the `toString()` method of the value, as the former works when used on [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) and {{jsxref("undefined")}}. For example:
```js
// You cannot access properties on null or undefined
const nullVar = null;
nullVar.toString(); // TypeError: Cannot read properties of null
String(nullVar); // "null"
const undefinedVar = undefined;
undefinedVar.toString(); // TypeError: Cannot read properties of undefined
String(undefinedVar); // "undefined"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Text formatting](/en-US/docs/Web/JavaScript/Guide/Text_formatting) guide
- {{jsxref("RegExp")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/codepointat/index.md | ---
title: String.prototype.codePointAt()
slug: Web/JavaScript/Reference/Global_Objects/String/codePointAt
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.codePointAt
---
{{JSRef}}
The **`codePointAt()`** method of {{jsxref("String")}} values returns a non-negative integer that is the Unicode code point value of the character starting at the given index. Note that the index is still based on UTF-16 code units, not Unicode code points.
{{EmbedInteractiveExample("pages/js/string-codepointat.html", "shorter")}}
## Syntax
```js-nolint
codePointAt(index)
```
### Parameters
- `index`
- : Zero-based index of the character to be returned. [Converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) — `undefined` is converted to 0.
### Return value
A non-negative integer representing the code point value of the character at the given `index`.
- If `index` is out of the range of `0` – `str.length - 1`, `codePointAt()` returns {{jsxref("undefined")}}.
- If the element at `index` is a UTF-16 leading surrogate, returns the code point of the surrogate _pair_.
- If the element at `index` is a UTF-16 trailing surrogate, returns _only_ the trailing surrogate code unit.
## Description
Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last character in a string called `str` is `str.length - 1`.
Unicode code points range from `0` to `1114111` (`0x10FFFF`). In UTF-16, each string index is a code unit with value `0` – `65535`. Higher code points are represented by _a pair_ of 16-bit surrogate pseudo-characters. Therefore, `codePointAt()` returns a code point that may span two string indices. For information on Unicode, see [UTF-16 characters, Unicode code points, and grapheme clusters](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters).
## Examples
### Using codePointAt()
```js
"ABC".codePointAt(0); // 65
"ABC".codePointAt(0).toString(16); // 41
"😍".codePointAt(0); // 128525
"\ud83d\ude0d".codePointAt(0); // 128525
"\ud83d\ude0d".codePointAt(0).toString(16); // 1f60d
"😍".codePointAt(1); // 56845
"\ud83d\ude0d".codePointAt(1); // 56845
"\ud83d\ude0d".codePointAt(1).toString(16); // de0d
"ABC".codePointAt(42); // undefined
```
### Looping with codePointAt()
Because using string indices for looping causes the same code point to be visited twice (once for the leading surrogate, once for the trailing surrogate), and the second time `codePointAt()` returns _only_ the trailing surrogate, it's better to avoid looping by index.
```js example-bad
const str = "\ud83d\udc0e\ud83d\udc71\u2764";
for (let i = 0; i < str.length; i++) {
console.log(str.codePointAt(i).toString(16));
}
// '1f40e', 'dc0e', '1f471', 'dc71', '2764'
```
Instead, use a [`for...of`](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement) statement or [spread the string](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax), both of which invoke the string's [`@@iterator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@iterator), which iterates by code points. Then, use `codePointAt(0)` to get the code point of each element.
```js
for (const codePoint of str) {
console.log(codePoint.codePointAt(0).toString(16));
}
// '1f40e', '1f471', '2764'
[...str].map((cp) => cp.codePointAt(0).toString(16));
// ['1f40e', '1f471', '2764']
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.codePointAt` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.fromCodePoint()")}}
- {{jsxref("String.fromCharCode()")}}
- {{jsxref("String.prototype.charCodeAt()")}}
- {{jsxref("String.prototype.charAt()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/towellformed/index.md | ---
title: String.prototype.toWellFormed()
slug: Web/JavaScript/Reference/Global_Objects/String/toWellFormed
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.toWellFormed
---
{{JSRef}}
The **`toWellFormed()`** method of {{jsxref("String")}} values returns a string where all [lone surrogates](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters) of this string are replaced with the Unicode replacement character U+FFFD.
## Syntax
```js-nolint
toWellFormed()
```
### Parameters
None.
### Return value
A new string that is a copy of this string, with all lone surrogates replaced with the Unicode replacement character U+FFFD. If `str` [is well formed](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/isWellFormed), a new string is still returned (essentially a copy of `str`).
## 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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters) section.
`toWellFormed()` iterates through the code units of this string, and replaces any lone surrogates with the [Unicode replacement character](<https://en.wikipedia.org/wiki/Specials_(Unicode_block)#Replacement_character>) U+FFFD `�`. This ensures that the returned string is well-formed and can be used in functions that expect well-formed strings, such as {{jsxref("encodeURI")}}. Compared to a custom implementation, `toWellFormed()` is more efficient, as engines can directly access the internal representation of strings.
When ill-formed strings are used in certain contexts, such as {{domxref("TextEncoder")}}, they are automatically converted to well-formed strings using the same replacement character. When lone surrogates are rendered, they are also rendered as the replacement character (a diamond with a question mark inside).
## Examples
### Using toWellFormed()
```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.toWellFormed());
}
// Logs:
// "ab�"
// "ab�c"
// "�ab"
// "c�ab"
// "abc"
// "ab😄c"
```
### Avoiding errors in encodeURI()
{{jsxref("encodeURI")}} throws an error if the string passed is not well-formed. This can be avoided by using `toWellFormed()` to convert the string to a well-formed string first.
```js
const illFormed = "https://example.com/search?q=\uD800";
try {
encodeURI(illFormed);
} catch (e) {
console.log(e); // URIError: URI malformed
}
console.log(encodeURI(illFormed.toWellFormed())); // "https://example.com/search?q=%EF%BF%BD"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.toWellFormed` in `core-js`](https://github.com/zloirock/core-js#well-formed-unicode-strings)
- {{jsxref("String.prototype.isWellFormed()")}}
- {{jsxref("String.prototype.normalize()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/matchall/index.md | ---
title: String.prototype.matchAll()
slug: Web/JavaScript/Reference/Global_Objects/String/matchAll
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.matchAll
---
{{JSRef}}
The **`matchAll()`** method of {{jsxref("String")}} values returns an iterator of all results matching this string against a [regular expression](/en-US/docs/Web/JavaScript/Guide/Regular_expressions), including [capturing groups](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences).
{{EmbedInteractiveExample("pages/js/string-matchall.html")}}
## Syntax
```js-nolint
matchAll(regexp)
```
### Parameters
- `regexp`
- : A regular expression object, or any object that has a [`Symbol.matchAll`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/matchAll) method.
If `regexp` is not a `RegExp` object and does not have a `Symbol.matchAll` method, it is implicitly converted to a {{jsxref("RegExp")}} by using `new RegExp(regexp, 'g')`.
If `regexp` [is a regex](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes), then it must have the global (`g`) flag set, or a {{jsxref("TypeError")}} is thrown.
### Return value
An [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) (which is not restartable) of matches or an empty iterator if no matches are found. Each value yielded by the iterator is an array with the same shape as the return value of {{jsxref("RegExp.prototype.exec()")}}.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the `regexp` [is a regex](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`).
## Description
The implementation of `String.prototype.matchAll` itself is very simple — it simply calls the `Symbol.matchAll` method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes from [`RegExp.prototype[@@matchAll]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll).
## Examples
### Regexp.prototype.exec() and matchAll()
Without `matchAll()`, it's possible to use calls to [`regexp.exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) (and regexes with the `g` flag) in a loop to obtain all the matches:
```js
const regexp = /foo[a-z]*/g;
const str = "table football, foosball";
let match;
while ((match = regexp.exec(str)) !== null) {
console.log(
`Found ${match[0]} start=${match.index} end=${regexp.lastIndex}.`,
);
}
// Found football start=6 end=14.
// Found foosball start=16 end=24.
```
With `matchAll()` available, you can avoid the {{jsxref("Statements/while", "while")}} loop and `exec` with `g`. Instead, you get an iterator to use with the more convenient {{jsxref("Statements/for...of", "for...of")}}, [array spreading](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax), or {{jsxref("Array.from()")}} constructs:
```js
const regexp = /foo[a-z]*/g;
const str = "table football, foosball";
const matches = str.matchAll(regexp);
for (const match of matches) {
console.log(
`Found ${match[0]} start=${match.index} end=${
match.index + match[0].length
}.`,
);
}
// Found football start=6 end=14.
// Found foosball start=16 end=24.
// matches iterator is exhausted after the for...of iteration
// Call matchAll again to create a new iterator
Array.from(str.matchAll(regexp), (m) => m[0]);
// [ "football", "foosball" ]
```
`matchAll` will throw an exception if the `g` flag is missing.
```js
const regexp = /[a-c]/;
const str = "abc";
str.matchAll(regexp);
// TypeError
```
`matchAll` internally makes a clone of the `regexp` — so, unlike {{jsxref("RegExp/exec", "regexp.exec()")}}, `lastIndex` does not change as the string is scanned.
```js
const regexp = /[a-c]/g;
regexp.lastIndex = 1;
const str = "abc";
Array.from(str.matchAll(regexp), (m) => `${regexp.lastIndex} ${m[0]}`);
// [ "1 b", "1 c" ]
```
However, this means that unlike using [`regexp.exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) in a loop, you can't mutate `lastIndex` to make the regex advance or rewind.
### Better access to capturing groups (than String.prototype.match())
Another compelling reason for `matchAll` is the improved access to capture groups.
Capture groups are ignored when using {{jsxref("String/match", "match()")}} with the global `g` flag:
```js
const regexp = /t(e)(st(\d?))/g;
const str = "test1test2";
str.match(regexp); // ['test1', 'test2']
```
Using `matchAll`, you can access capture groups easily:
```js
const array = [...str.matchAll(regexp)];
array[0];
// ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', length: 4]
array[1];
// ['test2', 'e', 'st2', '2', index: 5, input: 'test1test2', length: 4]
```
### Using matchAll() with a non-RegExp implementing @@matchAll
If an object has a `Symbol.matchAll` method, it can be used as a custom matcher. The return value of `Symbol.matchAll` becomes the return value of `matchAll()`.
```js
const str = "Hmm, this is interesting.";
str.matchAll({
[Symbol.matchAll](str) {
return [["Yes, it's interesting."]];
},
}); // returns [["Yes, it's interesting."]]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.matchAll` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.match()")}}
- [Regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) guide
- [Groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences) guide
- {{jsxref("RegExp")}}
- {{jsxref("RegExp.prototype.exec()")}}
- {{jsxref("RegExp.prototype.test()")}}
- [`RegExp.prototype[@@matchAll]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/tolocalelowercase/index.md | ---
title: String.prototype.toLocaleLowerCase()
slug: Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.toLocaleLowerCase
---
{{JSRef}}
The **`toLocaleLowerCase()`** method of {{jsxref("String")}} values returns this string converted to lower case, according to any locale-specific case mappings.
{{EmbedInteractiveExample("pages/js/string-tolocalelowercase.html")}}
## Syntax
```js-nolint
toLocaleLowerCase()
toLocaleLowerCase(locales)
```
### Parameters
- `locales` {{optional_inline}}
- : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower 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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
Unlike other methods that use the `locales` argument, `toLocaleLowerCase()` does not allow locale matching. Therefore, after checking the validity of the `locales` argument, `toLocaleLowerCase()` 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 lower case, according to any
locale-specific case mappings.
## Description
The `toLocaleLowerCase()` method returns the value of the string converted
to lower case according to any locale-specific case mappings.
`toLocaleLowerCase()` does not affect the value of the string itself. In most
cases, this will produce the same result as {{jsxref("String/toLowerCase", "toLowerCase()")}}, 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.
## Examples
### Using toLocaleLowerCase()
```js
"ALPHABET".toLocaleLowerCase(); // 'alphabet'
"\u0130".toLocaleLowerCase("tr") === "i"; // true
"\u0130".toLocaleLowerCase("en-US") === "i"; // false
const locales = ["tr", "TR", "tr-TR", "tr-u-co-search", "tr-x-turkish"];
"\u0130".toLocaleLowerCase(locales) === "i"; // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("String.prototype.toLocaleUpperCase()")}}
- {{jsxref("String.prototype.toLowerCase()")}}
- {{jsxref("String.prototype.toUpperCase()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/fromcodepoint/index.md | ---
title: String.fromCodePoint()
slug: Web/JavaScript/Reference/Global_Objects/String/fromCodePoint
page-type: javascript-static-method
browser-compat: javascript.builtins.String.fromCodePoint
---
{{JSRef}}
The **`String.fromCodePoint()`** static method returns a string created from the specified sequence of code points.
{{EmbedInteractiveExample("pages/js/string-fromcodepoint.html", "shorter")}}
## Syntax
```js-nolint
String.fromCodePoint()
String.fromCodePoint(num1)
String.fromCodePoint(num1, num2)
String.fromCodePoint(num1, num2, /* …, */ numN)
```
### Parameters
- `num1`, …, `numN`
- : An integer between `0` and `0x10FFFF` (inclusive) representing a Unicode code point.
### Return value
A string created by using the specified sequence of code points.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if `numN` is not an integer, is less than `0`, or is greater than `0x10FFFF` after being converted to a number.
## Description
Because `fromCodePoint()` is a static method of `String`, you always use it as `String.fromCodePoint()`, rather than as a method of a `String` value you created.
Unicode code points range from `0` to `1114111` (`0x10FFFF`). In UTF-16, each string index is a code unit with value `0` – `65535`. Higher code points are represented by _a pair_ of 16-bit surrogate pseudo-characters. Therefore, `fromCodePoint()` may return a string whose [`length`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length) (in UTF-16 code units) is larger than the number of arguments passed. For information on Unicode, see [UTF-16 characters, Unicode code points, and grapheme clusters](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters).
## Examples
### Using fromCodePoint()
Valid input:
```js
String.fromCodePoint(42); // "*"
String.fromCodePoint(65, 90); // "AZ"
String.fromCodePoint(0x404); // "\u0404" === "Є"
String.fromCodePoint(0x2f804); // "\uD87E\uDC04"
String.fromCodePoint(194564); // "\uD87E\uDC04"
String.fromCodePoint(0x1d306, 0x61, 0x1d307); // "\uD834\uDF06a\uD834\uDF07"
```
Invalid input:
```js
String.fromCodePoint("_"); // RangeError
String.fromCodePoint(Infinity); // RangeError
String.fromCodePoint(-1); // RangeError
String.fromCodePoint(3.14); // RangeError
String.fromCodePoint(3e-2); // RangeError
String.fromCodePoint(NaN); // RangeError
```
### Compared to fromCharCode()
{{jsxref("String.fromCharCode()")}} cannot return supplementary characters (i.e. code points `0x010000` – `0x10FFFF`) by specifying their code point. Instead, it requires the UTF-16 surrogate pair in order to return a supplementary character:
```js
String.fromCharCode(0xd83c, 0xdf03); // Code Point U+1F303 "Night with
String.fromCharCode(55356, 57091); // Stars" === "\uD83C\uDF03"
```
`String.fromCodePoint()`, on the other hand, can return 4-byte supplementary characters, as well as the more common 2-byte BMP characters, by specifying their code point (which is equivalent to the UTF-32 code unit):
```js
String.fromCodePoint(0x1f303); // or 127747 in decimal
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.fromCodePoint` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.fromCharCode()")}}
- {{jsxref("String.prototype.charAt()")}}
- {{jsxref("String.prototype.codePointAt()")}}
- {{jsxref("String.prototype.charCodeAt()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/at/index.md | ---
title: String.prototype.at()
slug: Web/JavaScript/Reference/Global_Objects/String/at
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.at
---
{{JSRef}}
The **`at()`** method of {{jsxref("String")}} values takes an integer value and returns a new {{jsxref("String")}} consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character.
{{EmbedInteractiveExample("pages/js/string-at.html")}}
## Syntax
```js-nolint
at(index)
```
### Parameters
- `index`
- : The index (position) of the string character to be returned. Supports relative indexing from the end of the string when passed a negative index; i.e. if a negative number is used, the character returned will be found by counting back from the end of the string.
### Return value
A {{jsxref("String")}} consisting of the single UTF-16 code unit located at the specified position. Returns {{jsxref("undefined")}} if the given index can not be found.
## Examples
### Return the last character of a string
The following example provides a function which returns the last character found in a specified string.
```js
// A function which returns the last character of a given string
function returnLast(arr) {
return arr.at(-1);
}
let invoiceRef = "myinvoice01";
console.log(returnLast(invoiceRef)); // '1'
invoiceRef = "myinvoice02";
console.log(returnLast(invoiceRef)); // '2'
```
### Comparing methods
Here we compare different ways to select the penultimate (last but one) character of a {{jsxref("String")}}. Whilst all below methods are valid, it highlights the succinctness and readability of the `at()` method.
```js
const myString = "Every green bus drives fast.";
// Using length property and charAt() method
const lengthWay = myString.charAt(myString.length - 2);
console.log(lengthWay); // 't'
// Using slice() method
const sliceWay = myString.slice(-2, -1);
console.log(sliceWay); // 't'
// Using at() method
const atWay = myString.at(-2);
console.log(atWay); // 't'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.at` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.indexOf()")}}
- {{jsxref("String.prototype.lastIndexOf()")}}
- {{jsxref("String.prototype.charCodeAt()")}}
- {{jsxref("String.prototype.codePointAt()")}}
- {{jsxref("String.prototype.split()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/startswith/index.md | ---
title: String.prototype.startsWith()
slug: Web/JavaScript/Reference/Global_Objects/String/startsWith
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.startsWith
---
{{JSRef}}
The **`startsWith()`** method of {{jsxref("String")}} values determines whether this string begins with the characters of a specified string, returning `true` or `false` as appropriate.
{{EmbedInteractiveExample("pages/js/string-startswith.html")}}
## Syntax
```js-nolint
startsWith(searchString)
startsWith(searchString, position)
```
### Parameters
- `searchString`
- : The characters to be searched for at the start of this string. Cannot [be a regex](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). All values that are not regexes are [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), so omitting it or passing `undefined` causes `startsWith()` to search for the string `"undefined"`, which is rarely what you want.
- `position` {{optional_inline}}
- : The start position at which `searchString` is expected to be found (the index of `searchString`'s first character). Defaults to `0`.
### Return value
**`true`** if the given characters are found at the beginning of the string, including when `searchString` is an empty string; otherwise, **`false`**.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `searchString` [is a regex](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes).
## Description
This method lets you determine whether or not a string begins with another string. This method is case-sensitive.
## Examples
### Using startsWith()
```js
const str = "To be, or not to be, that is the question.";
console.log(str.startsWith("To be")); // true
console.log(str.startsWith("not to be")); // false
console.log(str.startsWith("not to be", 10)); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.startsWith` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.endsWith()")}}
- {{jsxref("String.prototype.includes()")}}
- {{jsxref("String.prototype.indexOf()")}}
- {{jsxref("String.prototype.lastIndexOf()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/match/index.md | ---
title: String.prototype.match()
slug: Web/JavaScript/Reference/Global_Objects/String/match
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.match
---
{{JSRef}}
The **`match()`** method of {{jsxref("String")}} values retrieves the result of matching this string against a [regular expression](/en-US/docs/Web/JavaScript/Guide/Regular_expressions).
{{EmbedInteractiveExample("pages/js/string-match.html", "shorter")}}
## Syntax
```js-nolint
match(regexp)
```
### Parameters
- `regexp`
- : A regular expression object, or any object that has a [`Symbol.match`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/match) method.
If `regexp` is not a `RegExp` object and does not have a `Symbol.match` method, it is implicitly converted to a {{jsxref("RegExp")}} by using `new RegExp(regexp)`.
If you don't give any parameter and use the `match()` method directly, you will get an {{jsxref("Array")}} with an empty string: `[""]`, because this is equivalent to `match(/(?:)/)`.
### Return value
An {{jsxref("Array")}} whose contents depend on the presence or absence of the global (`g`) flag, or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) if no matches are found.
- If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included.
- If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as {{jsxref("RegExp.prototype.exec()")}} (an array with some extra properties).
## Description
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]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match).
- If you need to know if a string matches a regular expression {{jsxref("RegExp")}}, use {{jsxref("RegExp.prototype.test()")}}.
- If you only want the first match found, you might want to use {{jsxref("RegExp.prototype.exec()")}} instead.
- If you want to obtain capture groups and the global flag is set, you need to use {{jsxref("RegExp.prototype.exec()")}} or {{jsxref("String.prototype.matchAll()")}} instead.
For more information about the semantics of `match()` when a regex is passed, see [`RegExp.prototype[@@match]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@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 {{jsxref("String.prototype.matchAll()")}} and [Advanced searching with flags](/en-US/docs/Web/JavaScript/Guide/Regular_expressions#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 {{jsxref("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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.match` in `core-js` with fixes and implementation of modern behavior like `Symbol.match` support](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.matchAll()")}}
- {{jsxref("RegExp")}}
- {{jsxref("RegExp.prototype.exec()")}}
- {{jsxref("RegExp.prototype.test()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/padend/index.md | ---
title: String.prototype.padEnd()
slug: Web/JavaScript/Reference/Global_Objects/String/padEnd
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.padEnd
---
{{JSRef}}
The **`padEnd()`** method of {{jsxref("String")}} values pads this string with a given
string (repeated, if needed) so that the resulting string reaches a given length. The
padding is applied from the end of this string.
{{EmbedInteractiveExample("pages/js/string-padend.html")}}
## Syntax
```js-nolint
padEnd(targetLength)
padEnd(targetLength, padString)
```
### Parameters
- `targetLength`
- : The length of the resulting string once the current `str` has
been padded. If the value is less than or equal to `str.length`, the
current string will be returned as-is.
- `padString` {{optional_inline}}
- : The string to pad the current `str` with. If
`padString` is too long to stay within
`targetLength`, it will be truncated: for left-to-right
languages the left-most part and for right-to-left languages the right-most will be
applied. The default value for this parameter is " "
(`U+0020`).
### Return value
A {{jsxref("String")}} of the specified `targetLength` with the
`padString` applied at the end of the current
`str`.
## Examples
### Using padEnd
```js
"abc".padEnd(10); // "abc "
"abc".padEnd(10, "foo"); // "abcfoofoof"
"abc".padEnd(6, "123456"); // "abc123"
"abc".padEnd(1); // "abc"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.padEnd` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.padStart()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/endswith/index.md | ---
title: String.prototype.endsWith()
slug: Web/JavaScript/Reference/Global_Objects/String/endsWith
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.endsWith
---
{{JSRef}}
The **`endsWith()`** method of {{jsxref("String")}} values determines whether a string ends with the characters of this string, returning `true` or `false` as appropriate.
{{EmbedInteractiveExample("pages/js/string-endswith.html")}}
## Syntax
```js-nolint
endsWith(searchString)
endsWith(searchString, endPosition)
```
### Parameters
- `searchString`
- : The characters to be searched for at the end of `str`. Cannot [be a regex](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). All values that are not regexes are [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), so omitting it or passing `undefined` causes `endsWith()` to search for the string `"undefined"`, which is rarely what you want.
- `endPosition` {{optional_inline}}
- : The end position at which `searchString` is expected to be found (the index of `searchString`'s last character plus 1). Defaults to `str.length`.
### Return value
**`true`** if the given characters are found at the end of the string, including when `searchString` is an empty string; otherwise, **`false`**.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `searchString` [is a regex](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes).
## Description
This method lets you determine whether or not a string ends with another string. This method is case-sensitive.
## Examples
### Using endsWith()
```js
const str = "To be, or not to be, that is the question.";
console.log(str.endsWith("question.")); // true
console.log(str.endsWith("to be")); // false
console.log(str.endsWith("to be", 19)); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.endsWith` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.startsWith()")}}
- {{jsxref("String.prototype.includes()")}}
- {{jsxref("String.prototype.indexOf()")}}
- {{jsxref("String.prototype.lastIndexOf()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/tostring/index.md | ---
title: String.prototype.toString()
slug: Web/JavaScript/Reference/Global_Objects/String/toString
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.toString
---
{{JSRef}}
The **`toString()`** method of {{jsxref("String")}} values returns this string value.
{{EmbedInteractiveExample("pages/js/string-tostring.html")}}
## Syntax
```js-nolint
toString()
```
### Parameters
None.
### Return value
A string representing the specified string value.
## Description
The {{jsxref("String")}} object overrides the `toString` method of {{jsxref("Object")}}; it does not inherit
{{jsxref("Object.prototype.toString()")}}. For `String` values, the `toString` method returns the string itself (if it's a primitive) or the string that the `String` object wraps. It has the exact same implementation as {{jsxref("String.prototype.valueOf()")}}.
The `toString()` method requires its `this` value to be a `String` primitive or wrapper object. It throws a {{jsxref("TypeError")}} for other `this` values without attempting to coerce them to string values.
Because `String` doesn't have a [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive) method, JavaScript calls the `toString()` method automatically when a `String` _object_ is used in a context expecting a string, such as in a [template literal](/en-US/docs/Web/JavaScript/Reference/Template_literals). However, String _primitive_ values do not consult the `toString()` method to be [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — since they are already strings, no conversion is performed.
```js
String.prototype.toString = () => "Overridden";
console.log(`${"foo"}`); // "foo"
console.log(`${new String("foo")}`); // "Overridden"
```
## Examples
### Using toString()
The following example displays the string value of a {{jsxref("String")}} object:
```js
const x = new String("Hello world");
console.log(x.toString()); // "Hello world"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("String.prototype.valueOf()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/slice/index.md | ---
title: String.prototype.slice()
slug: Web/JavaScript/Reference/Global_Objects/String/slice
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.slice
---
{{JSRef}}
The **`slice()`** method of {{jsxref("String")}} values extracts a section of this string and
returns it as a new string, without modifying the original string.
{{EmbedInteractiveExample("pages/js/string-slice.html", "taller")}}
## Syntax
```js-nolint
slice(indexStart)
slice(indexStart, indexEnd)
```
### Parameters
- `indexStart`
- : The index of the first character to include in the returned substring.
- `indexEnd` {{optional_inline}}
- : The index of the first character to exclude from the returned substring.
### Return value
A new string containing the extracted section of the string.
## Description
`slice()` extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string.
`slice()` extracts up to but not including `indexEnd`. For example, `str.slice(4, 8)` extracts the fifth character through the eighth character (characters indexed `4`, `5`, `6`, and `7`):
```plain
indexStart indexEnd
↓ ↓
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| T | h | e | | m | i | r | r | o | r |
m i r r
_______________
↑
Result
```
- If `indexStart >= str.length`, an empty string is returned.
- If `indexStart < 0`, the index is counted from the end of the string. More formally, in this case, the substring starts at `max(indexStart + str.length, 0)`.
- If `indexStart` is omitted, undefined, or cannot be [converted to a number](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion), it's treated as `0`.
- If `indexEnd` is omitted, undefined, or cannot be [converted to a number](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion), or if `indexEnd >= str.length`, `slice()` extracts to the end of the string.
- If `indexEnd < 0`, the index is counted from the end of the string. More formally, in this case, the substring ends at `max(indexEnd + str.length, 0)`.
- If `indexEnd <= indexStart` after normalizing negative values (i.e. `indexEnd` represents a character that's before `indexStart`), an empty string is returned.
## Examples
### Using slice() to create a new string
The following example uses `slice()` to create a new string.
```js
const str1 = "The morning is upon us."; // The length of str1 is 23.
const str2 = str1.slice(1, 8);
const str3 = str1.slice(4, -2);
const str4 = str1.slice(12);
const str5 = str1.slice(30);
console.log(str2); // he morn
console.log(str3); // morning is upon u
console.log(str4); // is upon us.
console.log(str5); // ""
```
### Using slice() with negative indexes
The following example uses `slice()` with negative indexes.
```js
const str = "The morning is upon us.";
str.slice(-3); // 'us.'
str.slice(-3, -1); // 'us'
str.slice(0, -1); // 'The morning is upon us'
str.slice(4, -1); // 'morning is upon us'
```
This example counts backwards from the end of the string by `11` to find the
start index and forwards from the start of the string by `16` to find the end
index.
```js
console.log(str.slice(-11, 16)); // "is u"
```
Here it counts forwards from the start by `11` to find the start index and
backwards from the end by `7` to find the end index.
```js
console.log(str.slice(11, -7)); // " is u"
```
These arguments count backwards from the end by `5` to find the start index
and backwards from the end by `1` to find the end index.
```js
console.log(str.slice(-5, -1)); // "n us"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("String.prototype.substr()")}}
- {{jsxref("String.prototype.substring()")}}
- {{jsxref("Array.prototype.slice()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/repeat/index.md | ---
title: String.prototype.repeat()
slug: Web/JavaScript/Reference/Global_Objects/String/repeat
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.repeat
---
{{JSRef}}
The **`repeat()`** method of {{jsxref("String")}} values constructs and returns a new string
which contains the specified number of copies of this string, concatenated together.
{{EmbedInteractiveExample("pages/js/string-repeat.html", "shorter")}}
## Syntax
```js-nolint
repeat(count)
```
### Parameters
- `count`
- : An integer between `0` and
{{jsxref("Number/POSITIVE_INFINITY", "+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
- {{jsxref("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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.repeat` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.concat()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/includes/index.md | ---
title: String.prototype.includes()
slug: Web/JavaScript/Reference/Global_Objects/String/includes
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.includes
---
{{JSRef}}
The **`includes()`** method of {{jsxref("String")}} values performs a case-sensitive search to determine whether a given string may be found within this string, returning `true` or `false` as appropriate.
{{EmbedInteractiveExample("pages/js/string-includes.html", "shorter")}}
## Syntax
```js-nolint
includes(searchString)
includes(searchString, position)
```
### Parameters
- `searchString`
- : A string to be searched for within `str`. Cannot [be a regex](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). All values that are not regexes are [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), so omitting it or passing `undefined` causes `includes()` to search for the string `"undefined"`, which is rarely what you want.
- `position` {{optional_inline}}
- : The position within the string at which to begin searching for `searchString`. (Defaults to `0`.)
### Return value
**`true`** if the search string is found anywhere within the given string, including when `searchString` is an empty string; otherwise, **`false`**.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `searchString` [is a regex](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes).
## Description
This method lets you determine whether or not a string includes another string.
### Case-sensitivity
The `includes()` method is case sensitive. For example, the following expression returns `false`:
```js
"Blue Whale".includes("blue"); // returns false
```
You can work around this constraint by transforming both the original string and the search string to all lowercase:
```js
"Blue Whale".toLowerCase().includes("blue"); // returns true
```
## Examples
### Using includes()
```js
const str = "To be, or not to be, that is the question.";
console.log(str.includes("To be")); // true
console.log(str.includes("question")); // true
console.log(str.includes("nonexistent")); // false
console.log(str.includes("To be", 1)); // false
console.log(str.includes("TO BE")); // false
console.log(str.includes("")); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.includes` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("Array.prototype.includes()")}}
- {{jsxref("TypedArray.prototype.includes()")}}
- {{jsxref("String.prototype.indexOf()")}}
- {{jsxref("String.prototype.lastIndexOf()")}}
- {{jsxref("String.prototype.startsWith()")}}
- {{jsxref("String.prototype.endsWith()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/substring/index.md | ---
title: String.prototype.substring()
slug: Web/JavaScript/Reference/Global_Objects/String/substring
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.substring
---
{{JSRef}}
The **`substring()`** method of {{jsxref("String")}} values returns the part of this string from the start index up to and excluding the end index, or to the end of the string if no end index is supplied.
{{EmbedInteractiveExample("pages/js/string-substring.html")}}
## Syntax
```js-nolint
substring(indexStart)
substring(indexStart, indexEnd)
```
### Parameters
- `indexStart`
- : The index of the first character to include in the returned substring.
- `indexEnd` {{optional_inline}}
- : The index of the first character to exclude from the returned substring.
### Return value
A new string containing the specified part of the given string.
## Description
`substring()` extracts characters from `indexStart` up to _but not including_ `indexEnd`. In particular:
- If `indexEnd` is omitted, `substring()` extracts characters to the end of the string.
- If `indexStart` is equal to `indexEnd`, `substring()` returns an empty string.
- If `indexStart` is greater than `indexEnd`, then the effect of `substring()` is as if the two arguments were swapped; see example below.
Any argument value that is less than `0` or greater than `str.length` is treated as if it were `0` and `str.length`, respectively.
Any argument value that is {{jsxref("NaN")}} is treated as if it were `0`.
## Examples
### Using substring()
The following example uses `substring()` to display characters from the
string `"Mozilla"`:
```js
const anyString = "Mozilla";
console.log(anyString.substring(0, 1)); // "M"
console.log(anyString.substring(1, 0)); // "M"
console.log(anyString.substring(0, 6)); // "Mozill"
console.log(anyString.substring(4)); // "lla"
console.log(anyString.substring(4, 7)); // "lla"
console.log(anyString.substring(7, 4)); // "lla"
console.log(anyString.substring(0, 7)); // "Mozilla"
console.log(anyString.substring(0, 10)); // "Mozilla"
```
### Using substring() with length property
The following example uses the `substring()` method and
{{jsxref("String/length", "length")}} property to extract the last characters of a
particular string. This method may be easier to remember, given that you don't need to
know the starting and ending indices as you would in the above examples.
```js
const text = "Mozilla";
// Takes 4 last characters of string
console.log(text.substring(text.length - 4)); // prints "illa"
// Takes 5 last characters of string
console.log(text.substring(text.length - 5)); // prints "zilla"
```
### The difference between substring() and substr()
There are subtle differences between the `substring()` and
{{jsxref("String/substr", "substr()")}} methods, so you should be careful not to get
them confused.
- The two parameters of `substr()` are `start` and `length`, while for `substring()`, they are `start` and `end`.
- `substr()`'s `start` index will wrap to the end of the string if it is negative, while `substring()` will clamp it to `0`.
- Negative lengths in `substr()` are treated as zero, while `substring()` will swap the two indexes if `end` is less than `start`.
Furthermore, `substr()` is considered a _legacy feature in ECMAScript_, so it is best to avoid using it if possible.
```js
const text = "Mozilla";
console.log(text.substring(2, 5)); // "zil"
console.log(text.substr(2, 3)); // "zil"
```
### Differences between substring() and slice()
The `substring()` and {{jsxref("String/slice", "slice()")}} methods are
almost identical, but there are a couple of subtle differences between the two,
especially in the way negative arguments are dealt with.
The `substring()` method swaps its two arguments if
`indexStart` is greater than `indexEnd`,
meaning that a string is still returned. The {{jsxref("String/slice", "slice()")}}
method returns an empty string if this is the case.
```js
const text = "Mozilla";
console.log(text.substring(5, 2)); // "zil"
console.log(text.slice(5, 2)); // ""
```
If either or both of the arguments are negative or `NaN`, the
`substring()` method treats them as if they were `0`.
```js
console.log(text.substring(-5, 2)); // "Mo"
console.log(text.substring(-5, -2)); // ""
```
`slice()` also treats `NaN` arguments as `0`, but when
it is given negative values it counts backwards from the end of the string to find the
indexes.
```js
console.log(text.slice(-5, 2)); // ""
console.log(text.slice(-5, -2)); // "zil"
```
See the {{jsxref("String/slice", "slice()")}} page for more examples with negative
numbers.
### Replacing a substring within a string
The following example replaces a substring within a string. It will replace both
individual characters and substrings. The function call at the end of the example
changes the string `Brave New World` to `Brave New Web`.
```js
// Replaces oldS with newS in the string fullS
function replaceString(oldS, newS, fullS) {
for (let i = 0; i < fullS.length; ++i) {
if (fullS.substring(i, i + oldS.length) === oldS) {
fullS =
fullS.substring(0, i) +
newS +
fullS.substring(i + oldS.length, fullS.length);
}
}
return fullS;
}
replaceString("World", "Web", "Brave New World");
```
Note that this can result in an infinite loop if `oldS` is itself a
substring of `newS` — for example, if you attempted to replace
`"World"` with `"OtherWorld"` here.
A better method for replacing strings is as follows:
```js
function replaceString(oldS, newS, fullS) {
return fullS.split(oldS).join(newS);
}
```
The code above serves as an example for substring operations. If you need to replace
substrings, most of the time you will want to use
{{jsxref("String.prototype.replace()")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("String.prototype.substr()")}}
- {{jsxref("String.prototype.slice()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/length/index.md | ---
title: "String: length"
slug: Web/JavaScript/Reference/Global_Objects/String/length
page-type: javascript-instance-data-property
browser-compat: javascript.builtins.String.length
---
{{JSRef}}
The **`length`** data property of a {{jsxref("String")}} value contains the length of the string in UTF-16 code units.
{{EmbedInteractiveExample("pages/js/string-length.html", "shorter")}}
## Value
A non-negative integer.
{{js_property_attributes(0, 0, 0)}}
## Description
This property returns the number of code units in the string. JavaScript uses [UTF-16](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters) encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by `length` to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, [mathematical symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols), or obscure Chinese characters, you may need to account for the difference between code units and characters.
The language specification requires strings to have a maximum length of 2<sup>53</sup> - 1 elements, which is the upper limit for [precise integers](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer.
- In V8 (used by Chrome and Node), the maximum length is 2<sup>29</sup> - 24 (\~1GiB). On 32-bit systems, the maximum length is 2<sup>28</sup> - 16 (\~512MiB).
- In Firefox, the maximum length is 2<sup>30</sup> - 2 (\~2GiB). Before Firefox 65, the maximum length was 2<sup>28</sup> - 1 (\~512MiB).
- In Safari, the maximum length is 2<sup>31</sup> - 1 (\~4GiB).
If you are working with large strings in other encodings (such as UTF-8 files or blobs), note that when you load the data into a JS string, the encoding always becomes UTF-16. The size of the string may be different from the size of the source file.
```js
const str1 = "a".repeat(2 ** 29 - 24); // Success
const str2 = "a".repeat(2 ** 29 - 23); // RangeError: Invalid string length
const buffer = new Uint8Array(2 ** 29 - 24).fill("a".codePointAt(0)); // This buffer is 512MiB in size
const str = new TextDecoder().decode(buffer); // This string is 1GiB in size
```
For an empty string, `length` is 0.
The static property `String.length` is unrelated to the length of strings. It's the [arity](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length) of the `String` function (loosely, the number of formal parameters it has), which is 1.
Since `length` counts code units instead of characters, if you want to get the number of characters, you can first split the string with its [iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@iterator), which iterates by characters:
```js
function getCharacterLength(str) {
// The string iterator that is used here iterates over characters,
// not mere code units
return [...str].length;
}
console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3
```
## Examples
### Basic usage
```js
const x = "Mozilla";
const empty = "";
console.log(`${x} is ${x.length} code units long`);
// Mozilla is 7 code units long
console.log(`The empty string has a length of ${empty.length}`);
// The empty string has a length of 0
```
### Strings with length not equal to the number of characters
```js
const emoji = "😄";
console.log(emoji.length); // 2
console.log([...emoji].length); // 1
const adlam = "𞤲𞥋𞤣𞤫";
console.log(adlam.length); // 8
console.log([...adlam].length); // 4
const formula = "∀𝑥∈ℝ,𝑥²≥0";
console.log(formula.length); // 11
console.log([...formula].length); // 9
```
### Assigning to length
Because string is a primitive, attempting to assign a value to a string's `length` property has no observable effect, and will throw in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode).
```js
const myString = "bluebells";
myString.length = 4;
console.log(myString); // "bluebells"
console.log(myString.length); // 9
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`Array`: `length`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/fontsize/index.md | ---
title: String.prototype.fontsize()
slug: Web/JavaScript/Reference/Global_Objects/String/fontsize
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.String.fontsize
---
{{JSRef}} {{Deprecated_Header}}
The **`fontsize()`** method of {{jsxref("String")}} values creates a string that embeds this string in a {{HTMLElement("font")}} element (`<font size="...">str</font>`), which causes this string to be displayed in the specified font size.
> **Note:** All [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. For the case of `fontsize()`, the `<font>` element itself has been removed from the HTML specification and shouldn't be used anymore. Web developers should use [CSS](/en-US/docs/Web/CSS) properties instead.
## Syntax
```js-nolint
fontsize(size)
```
### Parameters
- `size`
- : An integer between 1 and 7, or a string representing a signed integer between 1 and 7.
### Return value
A string beginning with a `<font size="size">` start tag (double quotes in `size` are replaced with `"`), then the text `str`, and then a `</font>` end tag.
## Description
The `fontsize()` method itself simply joins the string parts together without any validation or normalization. However, to create valid {{HTMLElement("font")}} elements, When you specify size as an integer, you set the font size of `str` to one of the 7 defined sizes. You can specify `size` as a string such as `"-2"` or `"+3"` to adjust the font size of `str` relative to 3, the default value.
## Examples
### Using fontsize()
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.fontsize(7);
```
This will create the following HTML:
```html
<font size="7">Hello, world</font>
```
> **Warning:** This markup is invalid, because `font` is no longer a valid element.
Instead of using `fontsize()` and creating HTML text directly, you should use CSS to manipulate fonts. For example, you can manipulate {{cssxref("font-size")}} through the {{domxref("HTMLElement/style", "element.style")}} attribute:
```js
document.getElementById("yourElemId").style.fontSize = "7pt";
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.fontsize` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods)
- {{HTMLElement("font")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/search/index.md | ---
title: String.prototype.search()
slug: Web/JavaScript/Reference/Global_Objects/String/search
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.search
---
{{JSRef}}
The **`search()`** method of {{jsxref("String")}} values executes a search for a match between a regular expression and this string, returning the index of the first match in the string.
{{EmbedInteractiveExample("pages/js/string-search.html")}}
## Syntax
```js-nolint
search(regexp)
```
### Parameters
- `regexp`
- : A regular expression object, or any object that has a [`Symbol.search`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/search) method.
If `regexp` is not a `RegExp` object and does not have a `Symbol.search` method, it is implicitly converted to a {{jsxref("RegExp")}} by using `new RegExp(regexp)`.
### Return value
The index of the first match between the regular expression and the given string, or `-1` if no match was found.
## Description
The implementation of `String.prototype.search()` itself is very simple — it simply calls the `Symbol.search` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@search]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search).
The `g` flag of `regexp` has no effect on the `search()` result, and the search always happens as if the regex's `lastIndex` is 0. For more information on the behavior of `search()`, see [`RegExp.prototype[@@search]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search).
When you want to know whether a pattern is found, and _also_ know its index within a string, use `search()`.
- If you only want to know if it exists, use the {{jsxref("RegExp.prototype.test()")}} method, which returns a boolean.
- If you need the content of the matched text, use {{jsxref("String.prototype.match()")}} or {{jsxref("RegExp.prototype.exec()")}}.
## Examples
### Using search()
The following example searches a string with two different regex objects to show a successful search (positive value) vs. an unsuccessful search (`-1`).
```js
const str = "hey JudE";
const re = /[A-Z]/;
const reDot = /[.]/;
console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J"
console.log(str.search(reDot)); // returns -1 cannot find '.' dot punctuation
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.search` in `core-js` with fixes and implementation of modern behavior like `Symbol.search` support](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [Regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) guide
- {{jsxref("String.prototype.match()")}}
- {{jsxref("RegExp.prototype.exec()")}}
- [`RegExp.prototype[@@search]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/split/index.md | ---
title: String.prototype.split()
slug: Web/JavaScript/Reference/Global_Objects/String/split
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.split
---
{{JSRef}}
The **`split()`** method of {{jsxref("String")}} values takes a pattern and divides this string into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
{{EmbedInteractiveExample("pages/js/string-split.html", "taller")}}
## Syntax
```js-nolint
split(separator)
split(separator, limit)
```
### Parameters
- `separator`
- : The pattern describing where each split should occur. Can be `undefined`, a string, or an object with a [`Symbol.split`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/split) method — the typical example being a {{jsxref("RegExp", "regular expression", "", 1)}}. Omitting `separator` or passing `undefined` causes `split()` to return an array with the calling string as a single element. All values that are not `undefined` or objects with a `@@split` method are [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion).
- `limit` {{optional_inline}}
- : A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified `separator`, but stops when `limit` entries have been placed in the array. Any leftover text is not included in the array at all.
- The array may contain fewer entries than `limit` if the end of the string is reached before the limit is reached.
- If `limit` is `0`, `[]` is returned.
### Return value
An {{jsxref("Array")}} of strings, split at each point where the `separator` occurs in the given string.
## Description
If `separator` is a non-empty string, the target string is split by all matches of the `separator` without including `separator` in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like `myString.split("\t")`. If `separator` contains multiple characters, that entire character sequence must be found in order to split. If `separator` appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If `separator` does not occur in `str`, the returned array contains one element consisting of the entire string.
If `separator` is an empty string (`""`), `str` is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string.
> **Note:** `"".split("")` is therefore the only way to produce an empty array when a string is passed as `separator` and `limit` is not `0`.
> **Warning:** When the empty string (`""`) is used as a separator, the string is **not** split by _user-perceived characters_ ([grapheme clusters](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)) or unicode characters (code points), but by UTF-16 code units. This destroys [surrogate pairs](https://unicode.org/faq/utf_bom.html#utf16-2). See ["How do you get a string to a character array in JavaScript?" on StackOverflow](https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402).
If `separator` is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode code points depends on if the regex is [Unicode-aware](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode).
```js
"😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ]
"😄😄".split(/(?:)/u); // [ "😄", "😄" ]
```
If `separator` is a regular expression with capturing groups, then each time `separator` matches, the captured groups (including any `undefined` results) are spliced into the output array. This behavior is specified by the regexp's [`Symbol.split`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/split) method.
If `separator` is an object with a [`Symbol.split`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/split) method, that method is called with the target string and `limit` as arguments, and `this` set to the object. Its return value becomes the return value of `split`.
Any other value will be coerced to a string before being used as separator.
## Examples
### Using split()
When the string is empty and a non-empty separator is specified, `split()` returns `[""]`. If the string and separator are both empty strings, an empty array is returned.
```js
const emptyString = "";
// string is empty and separator is non-empty
console.log(emptyString.split("a"));
// [""]
// string and separator are both empty strings
console.log(emptyString.split(emptyString));
// []
```
The following example defines a function that splits a string into an array of strings
using `separator`. After splitting the string, the function logs
messages indicating the original string (before the split), the separator used, the
number of elements in the array, and the individual array elements.
```js
function splitString(stringToSplit, separator) {
const arrayOfStrings = stringToSplit.split(separator);
console.log("The original string is:", stringToSplit);
console.log("The separator is:", separator);
console.log(
"The array has",
arrayOfStrings.length,
"elements:",
arrayOfStrings.join(" / "),
);
}
const tempestString = "Oh brave new world that has such people in it.";
const monthString = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";
const space = " ";
const comma = ",";
splitString(tempestString, space);
splitString(tempestString);
splitString(monthString, comma);
```
This example produces the following output:
```plain
The original string is: "Oh brave new world that has such people in it."
The separator is: " "
The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it.
The original string is: "Oh brave new world that has such people in it."
The separator is: "undefined"
The array has 1 elements: Oh brave new world that has such people in it.
The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
The separator is: ","
The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec
```
### Removing spaces from a string
In the following example, `split()` looks for zero or more spaces, followed
by a semicolon, followed by zero or more spaces—and, when found, removes the spaces and
the semicolon from the string. `nameList` is the array returned as a result
of `split()`.
```js
const names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ";
console.log(names);
const re = /\s*(?:;|$)\s*/;
const nameList = names.split(re);
console.log(nameList);
```
This logs two lines; the first line logs the original string, and the second line logs
the resulting array.
```plain
Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand
[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ]
```
### Returning a limited number of splits
In the following example, `split()` looks for spaces in a string and returns
the first 3 splits that it finds.
```js
const myString = "Hello World. How are you doing?";
const splits = myString.split(" ", 3);
console.log(splits); // [ "Hello", "World.", "How" ]
```
### Splitting with a `RegExp` to include parts of the separator in the result
If `separator` is a regular expression that contains capturing
parentheses `( )`, matched results are included in the array.
```js
const myString = "Hello 1 word. Sentence number 2.";
const splits = myString.split(/(\d)/);
console.log(splits);
// [ "Hello ", "1", " word. Sentence number ", "2", "." ]
```
> **Note:** `\d` matches the [character class](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) for digits between 0 and 9.
### Using a custom splitter
An object with a `Symbol.split` method can be used as a splitter with custom behavior.
The following example splits a string using an internal state consisting of an incrementing number:
```js
const splitByNumber = {
[Symbol.split](str) {
let num = 1;
let pos = 0;
const result = [];
while (pos < str.length) {
const matchPos = str.indexOf(num, pos);
if (matchPos === -1) {
result.push(str.substring(pos));
break;
}
result.push(str.substring(pos, matchPos));
pos = matchPos + String(num).length;
num++;
}
return result;
},
};
const myString = "a1bc2c5d3e4f";
console.log(myString.split(splitByNumber)); // [ "a", "bc", "c5d", "e", "f" ]
```
The following example uses an internal state to enforce certain behavior, and to ensure a "valid" result is produced.
```js
const DELIMITER = ";";
// Split the commands, but remove any invalid or unnecessary values.
const splitCommands = {
[Symbol.split](str, lim) {
const results = [];
const state = {
on: false,
brightness: {
current: 2,
min: 1,
max: 3,
},
};
let pos = 0;
let matchPos = str.indexOf(DELIMITER, pos);
while (matchPos !== -1) {
const subString = str.slice(pos, matchPos).trim();
switch (subString) {
case "light on":
// If the `on` state is already true, do nothing.
if (!state.on) {
state.on = true;
results.push(subString);
}
break;
case "light off":
// If the `on` state is already false, do nothing.
if (state.on) {
state.on = false;
results.push(subString);
}
break;
case "brightness up":
// Enforce a brightness maximum.
if (state.brightness.current < state.brightness.max) {
state.brightness.current += 1;
results.push(subString);
}
break;
case "brightness down":
// Enforce a brightness minimum.
if (state.brightness.current > state.brightness.min) {
state.brightness.current -= 1;
results.push(subString);
}
break;
}
if (results.length === lim) {
break;
}
pos = matchPos + DELIMITER.length;
matchPos = str.indexOf(DELIMITER, pos);
}
// If we broke early due to reaching the split `lim`, don't add the remaining commands.
if (results.length < lim) {
results.push(str.slice(pos).trim());
}
return results;
},
};
const commands =
"light on; brightness up; brightness up; brightness up; light on; brightness down; brightness down; light off";
console.log(commands.split(splitCommands, 3)); // ["light on", "brightness up", "brightness down"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.split` in `core-js` with fixes and implementation of modern behavior like `Symbol.split` support](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.charAt()")}}
- {{jsxref("String.prototype.indexOf()")}}
- {{jsxref("String.prototype.lastIndexOf()")}}
- {{jsxref("Array.prototype.join()")}}
- [Regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) guide
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.