# Contributors by commit history
https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/json/parse/index.md

# Original Wiki contributors
mfuji09
SebastianSimon
wbamberg
hikigaya58
fscholz
nakhodkiin
anonyco
SphinxKnight
Richienb
alattalatta
schalkneethling
whirr.click
bartolocarrasco
jameshkramer
keirog
david_ross
FredGandt
kdex
oksana-khristenko
ccoenen
NodeGuy
Sheppy
duraik3
eduardoboucas
yortus
jordanbtucker
kmaglione
ElFelli
Mingun
broadl21
georgebatalinski
ziyunfei
DCK
madarche
ethertank
evilpie
marcello.nuccio
Waldo


Function.prototype[Symbol.hasInstance]()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2017.
The [Symbol.hasInstance]()
method of Function
instances specifies the default procedure for determining if a constructor function recognizes an object as one of the constructor's instances. It is called by the instanceof
operator.
Syntax
func[Symbol.hasInstance](value)
Parameters
value
-
The object to test. Primitive values always return
false
.
Return value
true
if func.prototype
is in the prototype chain of value
; otherwise, false
. Always returns false
if value
is not an object or this
is not a function. If this
is a bound function, returns the result of an instanceof
test on value
and the underlying target function.
Exceptions
TypeError
-
Thrown if
this
is not a bound function andthis.prototype
is not an object.
Description
The instanceof
operator calls the [Symbol.hasInstance]()
method of the right-hand side whenever such a method exists. Because all functions inherit from Function.prototype
by default, they would all have the [Symbol.hasInstance]()
method, so most of the time, the Function.prototype[Symbol.hasInstance]()
method specifies the behavior of instanceof
when the right-hand side is a function. This method implements the default behavior of the instanceof
operator (the same algorithm when constructor
has no [Symbol.hasInstance]()
method).
Unlike most methods, the Function.prototype[Symbol.hasInstance]()
property is non-configurable and non-writable. This is a security feature to prevent the underlying target function of a bound function from being obtainable. See this Stack Overflow answer for an example.
Examples
Reverting to default instanceof behavior
You would rarely need to call this method directly. Instead, this method is called by the instanceof
operator. You should expect the two results to usually be equivalent.
class Foo {}
const foo = new Foo();
console.log(foo instanceof Foo === Foo[Symbol.hasInstance](foo)); // true
You may want to use this method if you want to invoke the default instanceof
behavior, but you don't know if a constructor has an overridden [Symbol.hasInstance]()
method.
class Foo {
static [Symbol.hasInstance](value) {
// A custom implementation
return false;
}
}
const foo = new Foo();
console.log(foo instanceof Foo); // false
console.log(Function.prototype[Symbol.hasInstance].call(Foo, foo)); // true
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-function.prototype-%symbol.hasinstance% |


Intl.ListFormat.prototype.formatToParts()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2021.
The formatToParts()
method of Intl.ListFormat
instances returns an array of objects representing each part of the formatted string that would be returned by format()
. It is useful for building custom strings from the locale-specific tokens.
Try it
const vehicles = ["Motorcycle", "Bus", "Car"];
const formatterEn = new Intl.ListFormat("en", {
style: "long",
type: "conjunction",
});
const formatterFr = new Intl.ListFormat("fr", {
style: "long",
type: "conjunction",
});
const partValuesEn = formatterEn.formatToParts(vehicles).map((p) => p.value);
const partValuesFr = formatterFr.formatToParts(vehicles).map((p) => p.value);
console.log(partValuesEn);
// Expected output: "["Motorcycle", ", ", "Bus", ", and ", "Car"]"
console.log(partValuesFr);
// Expected output: "["Motorcycle", ", ", "Bus", " et ", "Car"]"
Syntax
formatToParts(list)
Parameters
list
-
An iterable object, such as an Array, containing strings. Omitting it results in formatting the empty array, which could be slightly confusing, so it is advisable to always explicitly pass a list.
Return value
An Array
of objects containing the formatted list in parts. Each object has two properties, type
and value
, each containing a string. The string concatenation of value
, in the order provided, will result in the same string as format()
. The type
may be one of the following:
Examples
Using formatToParts()
const fruits = ["Apple", "Orange", "Pineapple"];
const myListFormat = new Intl.ListFormat("en-GB", {
style: "long",
type: "conjunction",
});
console.table(myListFormat.formatToParts(fruits));
// [
// { "type": "element", "value": "Apple" },
// { "type": "literal", "value": ", " },
// { "type": "element", "value": "Orange" },
// { "type": "literal", "value": " and " },
// { "type": "element", "value": "Pineapple" }
// ]
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # sec-Intl.ListFormat.prototype.formatToParts |


Date.prototype.toISOString()

Date.prototype.toISOString()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The toISOString()
method of Date
instances returns a string representing this date in the date time string format, a simplified format based on ISO 8601, which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ
or ±YYYYYY-MM-DDTHH:mm:ss.sssZ
, respectively). The timezone is always UTC, as denoted by the suffix Z
.
Try it
const event = new Date("05 October 2011 14:48 UTC");
console.log(event.toString());
// Expected output: "Wed Oct 05 2011 16:48:00 GMT+0200 (CEST)"
// Note: your timezone may vary
console.log(event.toISOString());
// Expected output: "2011-10-05T14:48:00.000Z"
Syntax
toISOString()
Parameters
None.
Return value
A string representing the given date in the date time string format according to universal time. It's the same format as the one required to be recognized by Date.parse()
.
Exceptions
RangeError
-
Thrown if the date is invalid or if it corresponds to a year that cannot be represented in the date string format.
Examples
Using toISOString()
const d = new Date(0);
console.log(d.toISOString()); // "1970-01-01T00:00:00.000Z"
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-date.prototype.toisostring |


Subtraction assignment (-=)

Subtraction assignment (-=)
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The subtraction assignment (-=
) operator performs subtraction on the two operands and assigns the result to the left operand.
Try it
let a = 2;
console.log((a -= 3));
// Expected output: -1
console.log((a -= "Hello"));
// Expected output: NaN
Syntax
js
x -= y
Description
x -= y
is equivalent to x = x - y
, except that the expression x
is only evaluated once.
Examples
Subtraction assignment using numbers
js
let bar = 5;
bar -= 2; // 3
Other non-BigInt values are coerced to numbers:
js
bar -= "foo"; // NaN
Subtraction assignment using BigInts
js
let foo = 3n;
foo -= 2n; // 1n
foo -= 1; // TypeError: Cannot mix BigInt and other types, use explicit conversions
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-assignment-operators |


Intl.NumberFormat() constructor

Intl.NumberFormat() constructor
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2017.
The Intl.NumberFormat()
constructor creates Intl.NumberFormat
objects.
Try it
const number = 123456.789;
console.log(
new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(
number,
),
);
// Expected output: "123.456,79 €"
// The Japanese yen doesn't use a minor unit
console.log(
new Intl.NumberFormat("ja-JP", { style: "currency", currency: "JPY" }).format(
number,
),
);
// Expected output: "￥123,457"
// Limit to three significant digits
console.log(
new Intl.NumberFormat("en-IN", { maximumSignificantDigits: 3 }).format(
number,
),
);
// Expected output: "1,23,000"
Syntax
new Intl.NumberFormat()
new Intl.NumberFormat(locales)
new Intl.NumberFormat(locales, options)
Intl.NumberFormat()
Intl.NumberFormat(locales)
Intl.NumberFormat(locales, options)
Note:
Intl.NumberFormat()
can be called with or without new
. Both create a new Intl.NumberFormat
instance. However, there's a special behavior when it's called without new
and the this
value is another Intl.NumberFormat
instance; see Return value.
Parameters
locales
Optional-
A string with a BCP 47 language tag or an
Intl.Locale
instance, or an array of such locale identifiers. The runtime's default locale is used whenundefined
is passed or when none of the specified locale identifiers is supported. For the general form and interpretation of thelocales
argument, see the parameter description on theIntl
main page.The following Unicode extension key is allowed:
nu
-
See
numberingSystem
.
This key can also be set with
options
(as listed below). When both are set, theoptions
property takes precedence. options
Optional-
An object. For ease of reading, the property list is broken into sections based on their purposes, including locale options, style options, digit options, and other options.
Locale options
localeMatcher
-
The locale matching algorithm to use. Possible values are
"lookup"
and"best fit"
; the default is"best fit"
. For information about this option, see Locale identification and negotiation. numberingSystem
-
The numbering system to use for number formatting, such as
"arab"
,"hans"
,"mathsans"
, and so on. For a list of supported numbering system types, seeIntl.supportedValuesOf()
; the default is locale dependent. This option can also be set through thenu
Unicode extension key; if both are provided, thisoptions
property takes precedence.
Style options
Depending on the style
used, some of them may be ignored, and others may be required:
style
-
The formatting style to use.
"decimal"
(default)-
For plain number formatting.
"currency"
-
For currency formatting.
"percent"
-
For percent formatting.
"unit"
-
For unit formatting.
currency
-
The currency to use in currency formatting. Possible values are the ISO 4217 currency codes, such as
"USD"
for the US dollar,"EUR"
for the euro, or"CNY"
for the Chinese RMB — seeIntl.supportedValuesOf()
. There is no default value; if thestyle
is"currency"
, thecurrency
property must be provided. It is normalized to uppercase. currencyDisplay
-
How to display the currency in currency formatting.
"code"
-
Use the ISO currency code.
"symbol"
(default)-
Use a localized currency symbol such as €.
"narrowSymbol"
-
Use a narrow format symbol ("$100" rather than "US$100").
"name"
-
Use a localized currency name such as
"dollar"
.
currencySign
-
In many locales, accounting format means to wrap the number with parentheses instead of appending a minus sign. Possible values are
"standard"
and"accounting"
; the default is"standard"
. unit
-
The unit to use in
unit
formatting. Possible values are listed inIntl.supportedValuesOf()
. Pairs of simple units can be concatenated with "-per-" to make a compound unit. There is no default value; if thestyle
is"unit"
, theunit
property must be provided. unitDisplay
-
The unit formatting style to use in
unit
formatting. Possible values are:"short"
(default)-
E.g.,
16 l
. "narrow"
-
E.g.,
16l
. "long"
-
E.g.,
16 litres
.
Digit options
The following properties are also supported by Intl.PluralRules
.
minimumIntegerDigits
-
The minimum number of integer digits to use. A value with a smaller number of integer digits than this number will be left-padded with zeros (to the specified length) when formatted. Possible values are from
1
to21
; the default is1
. minimumFractionDigits
-
The minimum number of fraction digits to use. Possible values are from
0
to100
; the default for plain number and percent formatting is0
; the default for currency formatting is the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information). See SignificantDigits/FractionDigits default values for when this default gets applied. maximumFractionDigits
-
The maximum number of fraction digits to use. Possible values are from
0
to100
; the default for plain number formatting is the larger ofminimumFractionDigits
and3
; the default for currency formatting is the larger ofminimumFractionDigits
and the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information); the default for percent formatting is the larger ofminimumFractionDigits
and 0. See SignificantDigits/FractionDigits default values for when this default gets applied. minimumSignificantDigits
-
The minimum number of significant digits to use. Possible values are from
1
to21
; the default is1
. See SignificantDigits/FractionDigits default values for when this default gets applied. maximumSignificantDigits
-
The maximum number of significant digits to use. Possible values are from
1
to21
; the default is21
. See SignificantDigits/FractionDigits default values for when this default gets applied. roundingPriority
-
Specify how rounding conflicts will be resolved if both "FractionDigits" (
minimumFractionDigits
/maximumFractionDigits
) and "SignificantDigits" (minimumSignificantDigits
/maximumSignificantDigits
) are specified. Possible values are:"auto"
(default)-
The result from the significant digits property is used.
"morePrecision"
-
The result from the property that results in more precision is used.
"lessPrecision"
-
The result from the property that results in less precision is used.
The value
"auto"
is normalized to"morePrecision"
ifnotation
is"compact"
and none of the four "FractionDigits"/"SignificantDigits" options are set.Note that for values other than
auto
the result with more precision is calculated from themaximumSignificantDigits
andmaximumFractionDigits
(minimum fractional and significant digit settings are ignored). roundingIncrement
-
Indicates the increment at which rounding should take place relative to the calculated rounding magnitude. Possible values are
1
,2
,5
,10
,20
,25
,50
,100
,200
,250
,500
,1000
,2000
,2500
, and5000
; the default is1
. It cannot be mixed with significant-digits rounding or any setting ofroundingPriority
other thanauto
. roundingMode
-
How decimals should be rounded. Possible values are:
"ceil"
-
Round toward +∞. Positive values round up. Negative values round "more positive".
"floor"
-
Round toward -∞. Positive values round down. Negative values round "more negative".
"expand"
-
Round away from 0. The magnitude of the value is always increased by rounding. Positive values round up. Negative values round "more negative".
"trunc"
-
Round toward 0. This magnitude of the value is always reduced by rounding. Positive values round down. Negative values round "less negative".
"halfCeil"
-
Ties toward +∞. Values above the half-increment round like
"ceil"
(towards +∞), and below like"floor"
(towards -∞). On the half-increment, values round like"ceil"
. "halfFloor"
-
Ties toward -∞. Values above the half-increment round like
"ceil"
(towards +∞), and below like"floor"
(towards -∞). On the half-increment, values round like"floor"
. "halfExpand"
(default)-
Ties away from 0. Values above the half-increment round like
"expand"
(away from zero), and below like"trunc"
(towards 0). On the half-increment, values round like"expand"
. "halfTrunc"
-
Ties toward 0. Values above the half-increment round like
"expand"
(away from zero), and below like"trunc"
(towards 0). On the half-increment, values round like"trunc"
. "halfEven"
-
Ties towards the nearest even integer. Values above the half-increment round like
"expand"
(away from zero), and below like"trunc"
(towards 0). On the half-increment values round towards the nearest even digit.
These options reflect the ICU user guide, where "expand" and "trunc" map to ICU "UP" and "DOWN", respectively. The rounding modes example below demonstrates how each mode works.
trailingZeroDisplay
-
The strategy for displaying trailing zeros on whole numbers. Possible values are:
"auto"
(default)-
Keep trailing zeros according to
minimumFractionDigits
andminimumSignificantDigits
. "stripIfInteger"
-
Remove the fraction digits if they are all zero. This is the same as
"auto"
if any of the fraction digits is non-zero.
SignificantDigits/FractionDigits default values
For the four options above (the FractionDigits
and SignificantDigits
options), we mentioned their defaults; however, these defaults are not unconditionally applied. They are only applied when the property is actually going to be used, which depends on the roundingPriority
and notation
settings. Specifically:
- If
roundingPriority
is not"auto"
, then all four options apply. - If
roundingPriority
is"auto"
and at least oneSignificantDigits
option is set, then theSignificantDigits
options apply and theFractionDigits
options are ignored. - If
roundingPriority
is"auto"
, and either at least oneFractionDigits
option is set ornotation
is not"compact"
, then theFractionDigits
options apply and theSignificantDigits
options are ignored. - If
roundingPriority
is"auto"
,notation
is"compact"
, and none of the four options are set, then they are set to{ minimumFractionDigits: 0, maximumFractionDigits: 0, minimumSignificantDigits: 1, maximumSignificantDigits: 2 }
, regardless of the defaults mentioned above, androundingPriority
is set to"morePrecision"
.
Other options
notation
-
The formatting that should be displayed for the number. Possible values are:
"standard"
(default)-
Plain number formatting.
"scientific"
-
Return the order-of-magnitude for formatted number.
"engineering"
-
Return the exponent of ten when divisible by three.
"compact"
-
String representing exponent; defaults to using the "short" form.
compactDisplay
-
Only used when
notation
is"compact"
. Possible values are"short"
and"long"
; the default is"short"
. useGrouping
-
Whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators.
"always"
-
Display grouping separators even if the locale prefers otherwise.
"auto"
-
Display grouping separators based on the locale preference, which may also be dependent on the currency.
"min2"
-
Display grouping separators when there are at least 2 digits in a group.
true
-
Same as
"always"
. false
-
Display no grouping separators.
The default is
"min2"
ifnotation
is"compact"
, and"auto"
otherwise. The string values"true"
and"false"
are accepted, but are always converted to the default value. signDisplay
-
When to display the sign for the number. Possible values are:
"auto"
(default)-
Sign display for negative numbers only, including negative zero.
"always"
-
Always display sign.
"exceptZero"
-
Sign display for positive and negative numbers, but not zero.
"negative"
-
Sign display for negative numbers only, excluding negative zero.
"never"
-
Never display sign.
Return value
A new Intl.NumberFormat
object.
Note: The text below describes behavior that is marked by the specification as "optional". It may not work in all environments. Check the browser compatibility table.
Normally, Intl.NumberFormat()
can be called with or without new
, and a new Intl.NumberFormat
instance is returned in both cases. However, if the this
value is an object that is instanceof
Intl.NumberFormat
(doesn't necessarily mean it's created via new Intl.NumberFormat
; just that it has Intl.NumberFormat.prototype
in its prototype chain), then the value of this
is returned instead, with the newly created Intl.NumberFormat
object hidden in a [Symbol(IntlLegacyConstructedSymbol)]
property (a unique symbol that's reused between instances).
const formatter = Intl.NumberFormat.call(
{ __proto__: Intl.NumberFormat.prototype },
"en-US",
{ notation: "scientific" },
);
console.log(Object.getOwnPropertyDescriptors(formatter));
// {
// [Symbol(IntlLegacyConstructedSymbol)]: {
// value: NumberFormat [Intl.NumberFormat] {},
// writable: false,
// enumerable: false,
// configurable: false
// }
// }
Note that there's only one actual Intl.NumberFormat
instance here: the one hidden in [Symbol(IntlLegacyConstructedSymbol)]
. Calling the format()
and resolvedOptions()
methods on formatter
would correctly use the options stored in that instance, but calling all other methods (e.g., formatRange()
) would fail with "TypeError: formatRange method called on incompatible Object", because those methods don't consult the hidden instance's options.
This behavior, called ChainNumberFormat
, does not happen when Intl.NumberFormat()
is called without new
but with this
set to anything else that's not an instanceof Intl.NumberFormat
. If you call it directly as Intl.NumberFormat()
, the this
value is Intl
, and a new Intl.NumberFormat
instance is created normally.
Exceptions
RangeError
-
Thrown in one of the following cases:
- A property that takes enumerated values (such as
style
,units
,currency
, and so on) is set to an invalid value. - Both
maximumFractionDigits
andminimumFractionDigits
are set, and they are set to different values. Note that depending on various formatting options, these properties can have default values. It is therefore possible to get this error even if you only set one of the properties.
- A property that takes enumerated values (such as
TypeError
-
Thrown if the
options.style
property is set to "unit" or "currency", and no value has been set for the corresponding propertyoptions.unit
oroptions.currency
.
Examples
Basic usage
In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
const amount = 3500;
console.log(new Intl.NumberFormat().format(amount));
// '3,500' if in US English locale
Decimal and percent formatting
const amount = 3500;
new Intl.NumberFormat("en-US", {
style: "decimal",
}).format(amount); // '3,500'
new Intl.NumberFormat("en-US", {
style: "percent",
}).format(amount); // '350,000%'
Unit formatting
If the style
is 'unit'
, a unit
property must be provided.
Optionally, unitDisplay
controls the unit formatting.
const amount = 3500;
new Intl.NumberFormat("en-US", {
style: "unit",
unit: "liter",
}).format(amount); // '3,500 L'
new Intl.NumberFormat("en-US", {
style: "unit",
unit: "liter",
unitDisplay: "long",
}).format(amount); // '3,500 liters'
Currency formatting
If the style
is 'currency'
, a currency
property
must be provided. Optionally, currencyDisplay
and
currencySign
control the unit formatting.
const amount = -3500;
new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(amount); // '-$3,500.00'
new Intl.NumberFormat("bn", {
style: "currency",
currency: "USD",
currencyDisplay: "name",
}).format(amount); // '-3,500.00 US dollars'
new Intl.NumberFormat("bn", {
style: "currency",
currency: "USD",
currencySign: "accounting",
}).format(amount); // '($3,500.00)'
Scientific, engineering or compact notations
Scientific and compact notation are represented by the notation
option and can be formatted like this:
new Intl.NumberFormat("en-US", {
notation: "scientific",
}).format(987654321);
// 9.877E8
new Intl.NumberFormat("pt-PT", {
notation: "scientific",
}).format(987654321);
// 9,877E8
new Intl.NumberFormat("en-GB", {
notation: "engineering",
}).format(987654321);
// 987.654E6
new Intl.NumberFormat("de", {
notation: "engineering",
}).format(987654321);
// 987,654E6
new Intl.NumberFormat("zh-CN", {
notation: "compact",
}).format(987654321);
// 9.9亿
new Intl.NumberFormat("fr", {
notation: "compact",
compactDisplay: "long",
}).format(987654321);
// 988 millions
new Intl.NumberFormat("en-GB", {
notation: "compact",
compactDisplay: "short",
}).format(987654321);
// 988M
Displaying signs
Display a sign for positive and negative numbers, but not zero:
new Intl.NumberFormat("en-US", {
style: "percent",
signDisplay: "exceptZero",
}).format(0.55);
// '+55%'
Note that when the currency sign is "accounting", parentheses might be used instead of a minus sign:
new Intl.NumberFormat("bn", {
style: "currency",
currency: "USD",
currencySign: "accounting",
signDisplay: "always",
}).format(-3500);
// '($3,500.00)'
FractionDigits, SignificantDigits and IntegerDigits
You can specify the minimum or maximum number of fractional, integer or significant digits to display when formatting a number.
Note:
If both significant and fractional digit limits are specified, then the actual formatting depends on the roundingPriority
.
Using FractionDigits and IntegerDigits
The integer and fraction digit properties indicate the number of digits to display before and after the decimal point, respectively. If the value to display has fewer integer digits than specified, it will be left-padded with zeros to the expected number. If it has fewer fractional digits, it will be right-padded with zeros. Both cases are shown below:
// Formatting adds zeros to display minimum integers and fractions
console.log(
new Intl.NumberFormat("en", {
minimumIntegerDigits: 3,
minimumFractionDigits: 4,
}).format(4.33),
);
// "004.3300"
If a value has more fractional digits than the specified maximum number, it will be rounded.
The way that it is rounded depends on the roundingMode
property (more details are provided in the rounding modes section).
Below the value is rounded from five fractional digits (4.33145
) to two (4.33
):
// Display value shortened to maximum number of digits
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 2,
}).format(4.33145),
);
// "4.33"
The minimum fractional digits have no effect if the value already has more than 2 fractional digits:
// Minimum fractions have no effect if value is higher precision.
console.log(
new Intl.NumberFormat("en", {
minimumFractionDigits: 2,
}).format(4.33145),
);
// "4.331"
Warning:
Watch out for default values as they may affect formatting even if not specified in your code.
The default maximum digit value is 3
for plain values, 2
for currency, and may have different values for other predefined types.
The formatted value above is rounded to 3 digits, even though we didn't specify the maximum digits!
This is because a default value of maximumFractionDigits
is set when we specify minimumFractionDigits
, and visa versa. The default values of maximumFractionDigits
and minimumFractionDigits
are 3
and 0
, respectively.
You can use resolvedOptions()
to inspect the formatter.
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 2,
}).resolvedOptions(),
);
// {
// …
// minimumIntegerDigits: 1,
// minimumFractionDigits: 0,
// maximumFractionDigits: 2,
// …
// }
console.log(
new Intl.NumberFormat("en", {
minimumFractionDigits: 2,
}).resolvedOptions(),
);
// {
// …
// minimumIntegerDigits: 1,
// minimumFractionDigits: 2,
// maximumFractionDigits: 3,
// …
// }
Using SignificantDigits
The number of significant digits is the total number of digits including both integer and fractional parts.
The maximumSignificantDigits
is used to indicate the total number of digits from the original value to display.
The examples below show how this works. Note in particular the last case: only the first digit is retained and the others are discarded/set to zero.
// Display 5 significant digits
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 5,
}).format(54.33145),
);
// "54.331"
// Max 2 significant digits
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(54.33145),
);
// "54"
// Max 1 significant digits
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 1,
}).format(54.33145),
);
// "50"
The minimumSignificantDigits
ensures that at least the specified number of digits are displayed, adding zeros to the end of the value if needed.
// Minimum 10 significant digits
console.log(
new Intl.NumberFormat("en", {
minimumSignificantDigits: 10,
}).format(54.33145),
);
// "54.33145000"
Warning:
Watch out for default values as they may affect formatting.
If only one SignificantDigits
property is used, then its counterpart will automatically be applied with the default value.
The default maximum and minimum significant digit values are 21 and 1, respectively.
Specifying significant and fractional digits at the same time
The fraction digits (minimumFractionDigits
/maximumFractionDigits
) and significant digits (minimumSignificantDigits
/maximumSignificantDigits
) are both ways of controlling how many fractional and leading digits should be formatted.
If both are used at the same time, it is possible for them to conflict.
These conflicts are resolved using the roundingPriority
property.
By default, this has a value of "auto"
, which means that if either minimumSignificantDigits
or maximumSignificantDigits
is specified, the fractional and integer digit properties will be ignored.
For example, the code below formats the value of 4.33145
with maximumFractionDigits: 3
, and then maximumSignificantDigits: 2
, and then both.
The value with both is the one set with maximumSignificantDigits
.
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 3,
}).format(4.33145),
);
// "4.331"
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(4.33145),
);
// "4.3"
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 3,
maximumSignificantDigits: 2,
}).format(4.33145),
);
// "4.3"
Using resolvedOptions()
to inspect the formatter, we can see that the returned object does not include maximumFractionDigits
when maximumSignificantDigits
or minimumSignificantDigits
are specified.
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 3,
maximumSignificantDigits: 2,
}).resolvedOptions(),
);
// {
// …
// minimumIntegerDigits: 1,
// minimumSignificantDigits: 1,
// maximumSignificantDigits: 2,
// …
// }
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 3,
minimumSignificantDigits: 2,
}).resolvedOptions(),
);
// {
// …
// minimumIntegerDigits: 1,
// minimumSignificantDigits: 2,
// maximumSignificantDigits: 21,
// …
// }
In addition to "auto"
, you can resolve conflicts by specifying roundingPriority
as "morePrecision"
or "lessPrecision"
.
The formatter calculates the precision using the values of maximumSignificantDigits
and maximumFractionDigits
.
The code below shows the format being selected for the three different rounding priorities:
const maxFracNF = new Intl.NumberFormat("en", {
maximumFractionDigits: 3,
});
console.log(`maximumFractionDigits:3 - ${maxFracNF.format(1.23456)}`);
// "maximumFractionDigits:2 - 1.235"
const maxSigNS = new Intl.NumberFormat("en", {
maximumSignificantDigits: 3,
});
console.log(`maximumSignificantDigits:3 - ${maxSigNS.format(1.23456)}`);
// "maximumSignificantDigits:3 - 1.23"
const bothAuto = new Intl.NumberFormat("en", {
maximumSignificantDigits: 3,
maximumFractionDigits: 3,
});
console.log(`auto - ${bothAuto.format(1.23456)}`);
// "auto - 1.23"
const bothLess = new Intl.NumberFormat("en", {
roundingPriority: "lessPrecision",
maximumSignificantDigits: 3,
maximumFractionDigits: 3,
});
console.log(`lessPrecision - ${bothLess.format(1.23456)}`);
// "lessPrecision - 1.23"
const bothMore = new Intl.NumberFormat("en", {
roundingPriority: "morePrecision",
maximumSignificantDigits: 3,
maximumFractionDigits: 3,
});
console.log(`morePrecision - ${bothMore.format(1.23456)}`);
// "morePrecision - 1.235"
Note that the algorithm can behave in an unintuitive way if a minimum value is specified without a maximum value.
The example below formats the value 1
specifying minimumFractionDigits: 2
(formatting to 1.00
) and minimumSignificantDigits: 2
(formatting to 1.0
).
Since 1.00
has more digits than 1.0
, this should be the result when prioritizing morePrecision
, but in fact the opposite is true:
const bothLess = new Intl.NumberFormat("en", {
roundingPriority: "lessPrecision",
minimumFractionDigits: 2,
minimumSignificantDigits: 2,
});
console.log(`lessPrecision - ${bothLess.format(1)}`);
// "lessPrecision - 1.00"
const bothMore = new Intl.NumberFormat("en", {
roundingPriority: "morePrecision",
minimumFractionDigits: 2,
minimumSignificantDigits: 2,
});
console.log(`morePrecision - ${bothMore.format(1)}`);
// "morePrecision - 1.0"
The reason for this is that only the "maximum precision" values are used for the calculation, and the default value of maximumSignificantDigits
is much higher than maximumFractionDigits
.
Note:
The working group have proposed a modification of the algorithm where the formatter should evaluate the result of using the specified fractional and significant digits independently (taking account of both minimum and maximum values).
It will then select the option that displays more fractional digits if morePrecision
is set, and fewer if lessPrecision
is set.
This will result in more intuitive behavior for this case.
Rounding modes
If a value has more fractional digits than allowed by the constructor options, the formatted value will be rounded to the specified number of fractional digits.
The way in which the value is rounded depends on the roundingMode
property.
Number formatters use halfExpand
rounding by default, which rounds values "away from zero" at the half-increment (in other words, the magnitude of the value is rounded up).
For a positive number, if the fractional digits to be removed are closer to the next increment (or on the half way point) then the remaining fractional digits will be rounded up, otherwise they are rounded down. This is shown below: 2.23 rounded to two significant digits is truncated to 2.2 because 2.23 is less than the half increment 2.25, while values of 2.25 and greater are rounded up to 2.3:
// Value below half-increment: round down.
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(2.23),
);
// "2.2"
// Value on or above half-increment: round up.
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(2.25),
);
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(2.28),
);
// "2.3"
// "2.3"
A negative number on or below the half-increment point is also rounded away from zero (becomes more negative):
// Value below half-increment: round down.
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(-2.23),
);
// "-2.2"
// Value on or above half-increment: round up.
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(-2.25),
);
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(-2.28),
);
// "-2.3"
// "-2.3"
The table below show the effect of different rounding modes for positive and negative values that are on and around the half-increment.
| rounding mode | 2.23 | 2.25 | 2.28 | -2.23 | -2.25 | -2.28 |
|---|---|---|---|---|---|---|
ceil |
2.3 | 2.3 | 2.3 | -2.2 | -2.2 | -2.2 |
floor |
2.2 | 2.2 | 2.2 | -2.3 | -2.3 | -2.3 |
expand |
2.3 | 2.3 | 2.3 | -2.3 | -2.3 | -2.3 |
trunc |
2.2 | 2.2 | 2.2 | -2.2 | -2.2 | -2.2 |
halfCeil |
2.2 | 2.3 | 2.3 | -2.2 | -2.2 | -2.3 |
halfFloor |
2.2 | 2.2 | 2.3 | -2.2 | -2.3 | -2.3 |
halfExpand |
2.2 | 2.3 | 2.3 | -2.2 | -2.3 | -2.3 |
halfTrunc |
2.2 | 2.2 | 2.3 | -2.2 | -2.2 | -2.3 |
halfEven |
2.2 | 2.2 | 2.3 | -2.2 | -2.2 | -2.3 |
When using halfEven
, its behavior also depends on the parity (odd or even) of the last digit of the rounded number. For example, the behavior of halfEven
in the table above is the same as halfTrunc
, because the magnitudes of all numbers are between a smaller "even" number (2.2) and a larger "odd" number (2.3). If the numbers are between ±2.3 and ±2.4, halfEven
will behave like halfExpand
instead. This behavior avoids consistently under- or over-estimating half-increments in a large data sample.
Using roundingIncrement
Sometimes we want to round the remaining fractional digits to some other increment than the next integer. For example, currencies for which the smallest coin is 5 cents might want to round the value to increments of 5, reflecting amounts that can actually be paid in cash.
This kind of rounding can be achieved with the roundingIncrement
property.
For example, if maximumFractionDigits
is 2 and roundingIncrement
is 5, then the number is rounded to the nearest 0.05:
const nf = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 2,
roundingIncrement: 5,
});
console.log(nf.format(11.29)); // "$11.30"
console.log(nf.format(11.25)); // "$11.25"
console.log(nf.format(11.22)); // "$11.20"
This particular pattern is referred to as "nickel rounding", where nickel is the colloquial name for a USA 5 cent coin.
To round to the nearest 10 cents ("dime rounding"), you could change roundingIncrement
to 10
.
const nf = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 2,
roundingIncrement: 10,
});
console.log(nf.format(11.29)); // "$11.30"
console.log(nf.format(11.25)); // "$11.30"
console.log(nf.format(11.22)); // "$11.20"
You can also use roundingMode
to change the rounding algorithm.
The example below shows how halfCeil
rounding can be used to round the value "less positive" below the half-rounding increment and "more positive" if above or on the half-increment.
The incremented digit is "0.05" so the half-increment is at .025 (below, this is shown at 11.225).
const nf = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 2,
roundingIncrement: 5,
roundingMode: "halfCeil",
});
console.log(nf.format(11.21)); // "$11.20"
console.log(nf.format(11.22)); // "$11.20"
console.log(nf.format(11.224)); // "$11.20"
console.log(nf.format(11.225)); // "$11.25"
console.log(nf.format(11.23)); // "$11.25"
If you need to change the number of digits, remember that minimumFractionDigits
and maximumFractionDigits
must both be set to the same value, or a RangeError
is thrown.
roundingIncrement
cannot be mixed with significant-digits rounding or any setting of roundingPriority
other than auto
.
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # sec-intl-numberformat-constructor |


Intl.DurationFormat

Intl.DurationFormat
Baseline
2025
Newly available
Since March 2025, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
The Intl.DurationFormat
object enables language-sensitive duration formatting.
Constructor
Intl.DurationFormat()
-
Creates a new
Intl.DurationFormat
object.
Static methods
Intl.DurationFormat.supportedLocalesOf()
-
Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Instance properties
These properties are defined on Intl.DurationFormat.prototype
and shared by all Intl.DurationFormat
instances.
Intl.DurationFormat.prototype.constructor
-
The constructor function that created the instance object. For
Intl.DurationFormat
instances, the initial value is theIntl.DurationFormat
constructor. Intl.DurationFormat.prototype[Symbol.toStringTag]
-
The initial value of the
[Symbol.toStringTag]
property is the string"Intl.DurationFormat"
. This property is used inObject.prototype.toString()
.
Instance methods
Intl.DurationFormat.prototype.format()
-
Getter function that formats a duration according to the locale and formatting options of this
DurationFormat
object. Intl.DurationFormat.prototype.formatToParts()
-
Returns an
Array
of objects representing the formatted duration in parts. Intl.DurationFormat.prototype.resolvedOptions()
-
Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.
Examples
Using Intl.DurationFormat
The examples below show how to use the Intl.DurationFormat
object to format a duration object with various locales and styles.
const duration = {
hours: 1,
minutes: 46,
seconds: 40,
};
// With style set to "long" and locale "fr-FR"
new Intl.DurationFormat("fr-FR", { style: "long" }).format(duration);
// "1 heure, 46 minutes et 40 secondes"
// With style set to "short" and locale "en"
new Intl.DurationFormat("en", { style: "short" }).format(duration);
// "1 hr, 46 min and 40 sec"
// With style set to "narrow" and locale "pt"
new Intl.DurationFormat("pt", { style: "narrow" }).format(duration);
// "1 h 46 min 40 s"
Specifications
| Specification |
|---|
| Intl.DurationFormat # durationformat-objects |


Number.prototype.toString()

Number.prototype.toString()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The toString()
method of Number
values returns a string representing this number value.
Try it
function hexColor(c) {
if (c < 256) {
return Math.abs(c).toString(16);
}
return 0;
}
console.log(hexColor(233));
// Expected output: "e9"
console.log(hexColor("11"));
// Expected output: "b"
Syntax
toString()
toString(radix)
Parameters
radix
Optional-
An integer in the range
2
through36
specifying the base to use for representing the number value. Defaults to 10.
Return value
A string representing the specified number value. Scientific notation is used if radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6.
Exceptions
RangeError
-
Thrown if
radix
is less than 2 or greater than 36. TypeError
-
Thrown if this method is invoked on an object that is not a
Number
.
Description
The Number
object overrides the toString
method of Object
; it does not inherit
Object.prototype.toString()
. For Number
values, the toString
method returns a string representation of the value in the specified radix.
For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) a
through f
are used.
If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a -
sign, not the two's complement of the number value.
Both 0
and -0
have "0"
as their string representation. Infinity
returns "Infinity"
and NaN
returns "NaN"
.
If the number is not a whole number, the decimal point .
is used to separate the decimal places. Scientific notation is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6. In this case, the returned string always explicitly specifies the sign of the exponent.
console.log((10 ** 21.5).toString()); // "3.1622776601683794e+21"
console.log((10 ** 21.5).toString(8)); // "526665530627250154000000"
The underlying representation for floating point numbers is base-2 scientific notation (see number encoding). However, the toString()
method doesn't directly use this most precise representation of the number value. Rather, the algorithm uses the least number of significant figures necessary to distinguish the output from adjacent number values. For example, if the number is large, there will be many equivalent string representations of the same floating point number, and toString()
will choose the one with the most 0s to the right (for any given radix).
console.log((1000000000000000128).toString()); // "1000000000000000100"
console.log(1000000000000000100 === 1000000000000000128); // true
On the other hand, Number.prototype.toFixed()
and Number.prototype.toPrecision()
allow you to specify the precision and can be more precise than toString()
.
The toString()
method requires its this
value to be a Number
primitive or wrapper object. It throws a TypeError
for other this
values without attempting to coerce them to number values.
Because Number
doesn't have a [Symbol.toPrimitive]()
method, JavaScript calls the toString()
method automatically when a Number
object is used in a context expecting a string, such as in a template literal. However, Number primitive values do not consult the toString()
method to be coerced to strings — rather, they are directly converted using the same algorithm as the initial toString()
implementation.
Number.prototype.toString = () => "Overridden";
console.log(`${1}`); // "1"
console.log(`${new Number(1)}`); // "Overridden"
Examples
Using toString()
const count = 10;
console.log(count.toString()); // "10"
console.log((17).toString()); // "17"
console.log((17.2).toString()); // "17.2"
const x = 6;
console.log(x.toString(2)); // "110"
console.log((254).toString(16)); // "fe"
console.log((-10).toString(2)); // "-1010"
console.log((-0xff).toString(2)); // "-11111111"
Converting radix of number strings
If you have a string representing a number in a non-decimal radix, you can use parseInt()
and toString()
to convert it to a different radix.
const hex = "CAFEBABE";
const bin = parseInt(hex, 16).toString(2); // "11001010111111101011101010111110"
Beware of loss of precision: if the original number string is too large (larger than Number.MAX_SAFE_INTEGER
, for example), you should use a BigInt
instead. However, the BigInt
constructor only has support for strings representing number literals (i.e., strings starting with 0b
, 0o
, 0x
). In case your original radix is not one of binary, octal, decimal, or hexadecimal, you may need to hand-write your radix converter, or use a library.
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-number.prototype.tostring |


Object.prototype.constructor

Object.prototype.constructor
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The constructor
data property of an 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.
Value
A reference to the constructor function that created the instance object.
Property attributes of Object.prototype.constructor | |
|---|---|
| Writable | yes |
| Enumerable | no |
| Configurable | yes |
Note:
This property is created by default on the 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) 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 Array
objects, and object literals create plain objects.
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
property. If you have a longer prototype chain, you can usually expect every object in the chain to have a constructor
property.
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
.
function Tree(name) {
this.name = name;
}
const theTree = new Tree("Redwood");
console.log(`theTree.constructor is ${theTree.constructor}`);
This example displays the following output:
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.
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.
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
, not constructor
:
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
for objects, or typeof
for primitives.
Changing the constructor of a constructor function's prototype
Every constructor has a prototype
property, which will become the instance's [[Prototype]]
when called via the 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:
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 [Symbol.species]
to create new instances of a class, but such cases are rare, and you should be using the 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.
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.
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, so constructor
won't be visited in for...in
loops — as it normally isn't.
If the code above looks like too much boilerplate, you may also consider using Object.setPrototypeOf()
to manipulate the prototype chain.
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.
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
:
// …
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
do.
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
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-object.prototype.constructor |


Date.prototype[Symbol.toPrimitive]()

Date.prototype[Symbol.toPrimitive]()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2017.
The [Symbol.toPrimitive]()
method of Date
instances returns a primitive value representing this date. It may either be a string or a number, depending on the hint given.
Try it
// Depending on timezone, your results will vary
const date = new Date("20 December 2019 14:48");
console.log(date[Symbol.toPrimitive]("string"));
// Expected output: "Fri Dec 20 2019 14:48:00 GMT+0530 (India Standard Time)"
console.log(date[Symbol.toPrimitive]("number"));
// Expected output: 1576833480000
Syntax
date[Symbol.toPrimitive](hint)
Parameters
hint
-
A string representing the type of the primitive value to return. The following values are valid:
"string"
or"default"
: The method should return a string."number"
: The method should return a number.
Return value
If hint
is "string"
or "default"
, this method returns a string by coercing the this
value to a string (first trying toString()
then trying valueOf()
).
If hint
is "number"
, this method returns a number by coercing the this
value to a number (first trying valueOf()
then trying toString()
).
Exceptions
TypeError
-
Thrown if the
hint
argument is not one of the three valid values.
Description
The [Symbol.toPrimitive]()
method is part of the type coercion protocol. JavaScript always calls the [Symbol.toPrimitive]()
method in priority to convert an object to a primitive value. You rarely need to invoke the [Symbol.toPrimitive]()
method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.
The [Symbol.toPrimitive]()
method of the Date
object returns a primitive value by either invoking this.valueOf()
and returning a number, or invoking this.toString()
and returning a string. It exists to override the default primitive coercion process to return a string instead of a number, because primitive coercion, by default, calls valueOf()
before toString()
. With the custom [Symbol.toPrimitive]()
, new Date(0) + 1
returns "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)1"
(a string) instead of 1
(a number).
Examples
Using [Symbol.toPrimitive]()
const d = new Date(0); // 1970-01-01T00:00:00.000Z
d[Symbol.toPrimitive]("string"); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"
d[Symbol.toPrimitive]("number"); // 0
d[Symbol.toPrimitive]("default"); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-date.prototype-%symbol.toprimitive% |


Temporal.Duration.prototype.seconds

Temporal.Duration.prototype.seconds
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
The seconds
accessor property of Temporal.Duration
instances returns an integer representing the number of seconds in the duration.
Unless the duration is balanced, you cannot assume the range of this value, but you can know its sign by checking the duration's sign
property. If it is balanced to a unit above seconds, the seconds
absolute value will be between 0 and 59, inclusive.
The set accessor of seconds
is undefined
. You cannot change this property directly. Use the with()
method to create a new Temporal.Duration
object with the desired new value.
Examples
Using seconds
js
const d1 = Temporal.Duration.from({ minutes: 1, seconds: 30 });
const d2 = Temporal.Duration.from({ minutes: -1, seconds: -30 });
const d3 = Temporal.Duration.from({ minutes: 1 });
const d4 = Temporal.Duration.from({ seconds: 60 });
console.log(d1.seconds); // 30
console.log(d2.seconds); // -30
console.log(d3.seconds); // 0
console.log(d4.seconds); // 60
// Balance d4
const d4Balanced = d4.round({ largestUnit: "minutes" });
console.log(d4Balanced.seconds); // 0
console.log(d4Balanced.minutes); // 1
Specifications
| Specification |
|---|
| Temporal # sec-get-temporal.duration.prototype.seconds |
Browser compatibility
See also
Temporal.Duration
Temporal.Duration.prototype.years
Temporal.Duration.prototype.months
Temporal.Duration.prototype.weeks
Temporal.Duration.prototype.days
Temporal.Duration.prototype.hours
Temporal.Duration.prototype.minutes
Temporal.Duration.prototype.milliseconds
Temporal.Duration.prototype.microseconds
Temporal.Duration.prototype.nanoseconds


Intl.DateTimeFormat

Intl.DateTimeFormat
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2017.
The Intl.DateTimeFormat
object enables language-sensitive date and time formatting.
Try it
const date = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));
// Results below assume UTC timezone - your results may vary
// Specify default date formatting for language (locale)
console.log(new Intl.DateTimeFormat("en-US").format(date));
// Expected output: "12/20/2020"
// Specify default date formatting for language with a fallback language (in this case Indonesian)
console.log(new Intl.DateTimeFormat(["ban", "id"]).format(date));
// Expected output: "20/12/2020"
// Specify date and time format using "style" options (i.e. full, long, medium, short)
console.log(
new Intl.DateTimeFormat("en-GB", {
dateStyle: "full",
timeStyle: "long",
timeZone: "Australia/Sydney",
}).format(date),
);
// Expected output: "Sunday, 20 December 2020 at 14:23:16 GMT+11"
Constructor
Intl.DateTimeFormat()
-
Creates a new
Intl.DateTimeFormat
object.
Static methods
Intl.DateTimeFormat.supportedLocalesOf()
-
Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Instance properties
These properties are defined on Intl.DateTimeFormat.prototype
and shared by all Intl.DateTimeFormat
instances.
Intl.DateTimeFormat.prototype.constructor
-
The constructor function that created the instance object. For
Intl.DateTimeFormat
instances, the initial value is theIntl.DateTimeFormat
constructor. Intl.DateTimeFormat.prototype[Symbol.toStringTag]
-
The initial value of the
[Symbol.toStringTag]
property is the string"Intl.DateTimeFormat"
. This property is used inObject.prototype.toString()
.
Instance methods
Intl.DateTimeFormat.prototype.format()
-
Getter function that formats a date according to the locale and formatting options of this
DateTimeFormat
object. Intl.DateTimeFormat.prototype.formatRange()
-
This method receives two Dates and formats the date range in the most concise way based on the locale and options provided when instantiating
DateTimeFormat
. Intl.DateTimeFormat.prototype.formatRangeToParts()
-
This method receives two Dates and returns an Array of objects containing the locale-specific tokens representing each part of the formatted date range.
Intl.DateTimeFormat.prototype.formatToParts()
-
Returns an
Array
of objects representing the date string in parts that can be used for custom locale-aware formatting. Intl.DateTimeFormat.prototype.resolvedOptions()
-
Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.
Examples
Using DateTimeFormat
In basic use without specifying a locale, DateTimeFormat
uses the default locale and default options.
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// toLocaleString without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(new Intl.DateTimeFormat().format(date));
// "12/19/2012" if run with en-US locale (language) and time zone America/Los_Angeles (UTC-0800)
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:
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// Results below use the time zone of America/Los_Angeles (UTC-0800, Pacific Standard Time)
// US English uses month-day-year order
console.log(new Intl.DateTimeFormat("en-US").format(date));
// "12/19/2012"
// British English uses day-month-year order
console.log(new Intl.DateTimeFormat("en-GB").format(date));
// "19/12/2012"
// Korean uses year-month-day order
console.log(new Intl.DateTimeFormat("ko-KR").format(date));
// "2012. 12. 19."
// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(new Intl.DateTimeFormat("ar-EG").format(date));
// "١٩/١٢/٢٠١٢"
// for Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(new Intl.DateTimeFormat("ja-JP-u-ca-japanese").format(date));
// "24/12/19"
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(new Intl.DateTimeFormat(["ban", "id"]).format(date));
// "19/12/2012"
Using options
The date and time formats can be customized using the options
argument:
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200));
// request a weekday along with a long date
let options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
console.log(new Intl.DateTimeFormat("de-DE", options).format(date));
// "Donnerstag, 20. Dezember 2012"
// an application may want to use UTC and make that visible
options.timeZone = "UTC";
options.timeZoneName = "short";
console.log(new Intl.DateTimeFormat("en-US", options).format(date));
// "Thursday, December 20, 2012, GMT"
// sometimes you want to be more precise
options = {
hour: "numeric",
minute: "numeric",
second: "numeric",
timeZone: "Australia/Sydney",
timeZoneName: "short",
};
console.log(new Intl.DateTimeFormat("en-AU", options).format(date));
// "2:00:00 pm AEDT"
// sometimes you want to be very precise
options.fractionalSecondDigits = 3; // number digits for fraction-of-seconds
console.log(new Intl.DateTimeFormat("en-AU", options).format(date));
// "2:00:00.200 pm AEDT"
// sometimes even the US needs 24-hour time
options = {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: false,
timeZone: "America/Los_Angeles",
};
console.log(new Intl.DateTimeFormat("en-US", options).format(date));
// "12/19/2012, 19:00:00"
// to specify options but use the browser's default locale, use undefined
console.log(new Intl.DateTimeFormat(undefined, options).format(date));
// "12/19/2012, 19:00:00"
// sometimes it's helpful to include the period of the day
options = { hour: "numeric", dayPeriod: "short" };
console.log(new Intl.DateTimeFormat("en-US", options).format(date));
// 10 at night
The used calendar and numbering formats can also be set independently via options
arguments:
const options = { calendar: "chinese", numberingSystem: "arab" };
const dateFormat = new Intl.DateTimeFormat(undefined, options);
const usedOptions = dateFormat.resolvedOptions();
console.log(usedOptions.calendar);
// "chinese"
console.log(usedOptions.numberingSystem);
// "arab"
console.log(usedOptions.timeZone);
// "America/New_York" (the users default timezone)
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # datetimeformat-objects |
Browser compatibility
See also
- Polyfill of
Intl.DateTimeFormat
in FormatJS Intl
Date.prototype.toLocaleString()
Date.prototype.toLocaleDateString()
Date.prototype.toLocaleTimeString()
Temporal.Instant.prototype.toLocaleString()
Temporal.PlainDate.prototype.toLocaleString()
Temporal.PlainDateTime.prototype.toLocaleString()
Temporal.PlainTime.prototype.toLocaleString()
Temporal.PlainYearMonth.prototype.toLocaleString()
Temporal.PlainMonthDay.prototype.toLocaleString()
Temporal.ZonedDateTime.prototype.toLocaleString()


JavaScript execution model

JavaScript execution model
This page introduces the basic infrastructure of the JavaScript runtime environment. The model is largely theoretical and abstract, without any platform-specific or implementation-specific details. Modern JavaScript engines heavily optimize the described semantics.
This page is a reference. It assumes you are already familiar with the execution model of other programming languages, such as C and Java. It makes heavy references to existing concepts in operating systems and programming languages.
The engine and the host
JavaScript execution requires the cooperation of two pieces of software: the JavaScript engine and the host environment.
The JavaScript engine implements the ECMAScript (JavaScript) language, providing the core functionality. It takes source code, parses it, and executes it. However, in order to interact with the outside world, such as to produce any meaningful output, to interface with external resources, or to implement security- or performance-related mechanisms, we need additional environment-specific mechanisms provided by the host environment. For example, the HTML DOM is the host environment when JavaScript is executed in a web browser. Node.js is another host environment that allows JavaScript to be run on the server side.
While we focus primarily on the mechanisms defined in ECMAScript in this reference, we will occasionally talk about mechanisms defined in the HTML spec, which is often mimicked by other host environments like Node.js or Deno. This way, we can give a coherent picture of the JavaScript execution model as used on the web and beyond.
Agent execution model
In the JavaScript specification, each autonomous executor of JavaScript is called an agent, which maintains its facilities for code execution:
- Heap (of objects): this is just a name to denote a large (mostly unstructured) region of memory. It gets populated as objects get created in the program. Note that in the case of shared memory, each agent has its own heap with its own version of a
SharedArrayBuffer
object, but the underlying memory represented by the buffer is shared. - Queue (of jobs): this is known in HTML (and also commonly) as the event loop which enables asynchronous programming in JavaScript while being single-threaded. It's called a queue because it's generally first-in-first-out: earlier jobs are executed before later ones.
- Stack (of execution contexts): this is what's known as a call stack and allows transferring control flow by entering and exiting execution contexts like functions. It's called a stack because it's last-in-first-out. Every job enters by pushing a new frame onto the (empty) stack, and exits by emptying the stack.
These are three distinct data structures that keep track of different data. We will introduce the queue and the stack in more detail in the following sections. To read more about how heap memory is allocated and freed, see memory management.
Each agent is analogous to a thread (note that the underlying implementation may or may not be an actual operating system thread). Each agent can own multiple realms (which 1-to-1 correlate with global objects) that can synchronously access each other, and thus needs to run in a single execution thread. An agent also has a single memory model, indicating whether it's little-endian, whether it can be synchronously blocked, whether atomic operations are lock-free, etc.
An agent on the web can be one of the following:
- A Similar-origin window agent, which contains various
Window
objects which can potentially reach each other, either directly or by usingdocument.domain
. If the window is origin-keyed, then only same-origin windows can reach each other. - A Dedicated worker agent containing a single
DedicatedWorkerGlobalScope
. - A Shared worker agent containing a single
SharedWorkerGlobalScope
. - A Service worker agent containing a single
ServiceWorkerGlobalScope
. - A Worklet agent containing a single
WorkletGlobalScope
.
In other words, each worker creates its own agent, while one or more windows may be within the same agent—usually a main document and its similar-origin iframes. In Node.js, a similar concept called worker threads is available.
The diagram below illustrates the execution model of agents:
Realms
Each agent owns one or more realms. Each piece of JavaScript code is associated with a realm when it's loaded, which remains the same even when called from another realm. A realm consists of the following information:
- A list of intrinsic objects like
Array
,Array.prototype
, etc. - Globally declared variables, the value of
globalThis
, and the global object - A cache of template literal arrays, because evaluation of the same tagged template literal expression always causes the tag to receive the same array object
On the web, the realm and the global object are 1-to-1 corresponded. The global object is either a Window
, a WorkerGlobalScope
, or a WorkletGlobalScope
. So for example, every iframe
executes in a different realm, though it may be in the same agent as the parent window.
Realms are usually mentioned when talking about the identities of global objects. For example, we need methods such as Array.isArray()
or Error.isError()
, because an array constructed in another realm will have a different prototype object than the Array.prototype
object in the current realm, so instanceof Array
will wrongly return false
.
Stack and execution contexts
We first consider synchronous code execution. Each job enters by calling its associated callback. Code inside this callback may create variables, call functions, or exit. Each function needs to keep track of its own variable environments and where to return to. To handle this, the agent needs a stack to keep track of the execution contexts. An execution context, also known generally as a stack frame, is the smallest unit of execution. It tracks the following information:
- Code evaluation state
- The module or script, the function (if applicable), and the currently executing generator that contains this code
- The current realm
- Bindings, including:
- Variables defined with
var
,let
,const
,function
,class
, etc. - Private identifiers like
#foo
which are only valid in the current context this
reference
- Variables defined with
Imagine a program consisting of a single job defined by the following code:
function foo(b) {
const a = 10;
return a + b + 11;
}
function bar(x) {
const y = 3;
return foo(x * y);
}
const baz = bar(7); // assigns 42 to baz
- When the job starts, the first frame is created, where the variables
foo
,bar
, andbaz
are defined. It callsbar
with the argument7
. - A second frame is created for the
bar
call, containing bindings for the parameterx
and the local variabley
. It first performs the multiplicationx * y
, then callsfoo
with the result. - A third frame is created for the
foo
call, containing bindings for the parameterb
and the local variablea
. It first performs the additiona + b + 11
, then returns the result. - When
foo
returns, the top frame element is popped out of the stack, and the call expressionfoo(x * y)
resolves to the return value. It then continues execution, which is just to return this result. - When
bar
returns, the top frame element is popped out of the stack, and the call expressionbar(7)
resolves to the return value. This initializesbaz
with the return value. - We reach the end of the job's source code, so the stack frame for the entrypoint is popped out of the stack. The stack is empty, so the job is considered completed.
Generators and reentry
When a frame is popped, it's not necessarily gone forever, because sometimes we need to come back to it. For example, consider a generator function:
function* gen() {
console.log(1);
yield;
console.log(2);
}
const g = gen();
g.next(); // logs 1
g.next(); // logs 2
In this case, calling gen()
first creates an execution context which is suspended—no code inside gen
gets executed yet. The generator g
saves this execution context internally. The current running execution context remains to be the entrypoint. When g.next()
is called, the execution context for gen
is pushed onto the stack, and the code inside gen
is executed until the yield
expression. Then, the generator execution context gets suspended and removed from the stack, which returns control back to the entrypoint. When g.next()
is called again, the generator execution context is pushed back onto the stack, and the code inside gen
resumes from where it left off.
Tail calls
One mechanism defined in the specification is proper tail call (PTC). A function call is a tail call if the caller does nothing after the call except return the value:
function f() {
return g();
}
In this case, the call to g
is a tail call. If a function call is in tail position, the engine is required to discard the current execution context and replace it with the context of the tail call, instead of pushing a new frame for the g()
call. This means that tail recursion is not subject to the stack size limits:
function factorial(n, acc = 1) {
if (n <= 1) return acc;
return factorial(n - 1, n * acc);
}
In reality, discarding the current frame causes debugging problems, because if g()
throws an error, f
is no longer on the stack and won't appear in the stack trace. Currently, only Safari (JavaScriptCore) implements PTC, and they have invented some specific infrastructure to address the debuggability issue.
Closures
Another interesting phenomenon related to variable scoping and function calls is closures. Whenever a function is created, it also memorizes internally the variable bindings of the current running execution context. Then, these variable bindings can outlive the execution context.
let f;
{
let x = 10;
f = () => x;
}
console.log(f()); // logs 10
Job queue and event loop
An agent is a thread, which means the interpreter can only process one statement at a time. When the code is all synchronous, this is fine because we can always make progress. But if the code needs to perform asynchronous action, then we cannot progress unless that action is completed. However, it would be detrimental to user experience if that halts the whole program—the nature of JavaScript as a web scripting language requires it to be never blocking. Therefore, the code that handles the completion of that asynchronous action is defined as a callback. This callback defines a job, which gets placed into a job queue—or, in HTML terminology, an event loop—once the action is completed.
Every time, the agent pulls a job from the queue and executes it. When the job is executed, it may create more jobs, which are added to the end of the queue. Jobs can also be added via the completion of asynchronous platform mechanisms, such as timers, I/O, and events. A job is considered completed when the stack is empty; then, the next job is pulled from the queue. Jobs might not be pulled with uniform priority—for example, HTML event loops split jobs into two categories: tasks and microtasks. Microtasks have higher priority and the microtask queue is drained first before the task queue is pulled. For more information, check the HTML microtask guide. If the job queue is empty, the agent waits for more jobs to be added.
"Run-to-completion"
Each job is processed completely before any other job is processed. This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be preempted and will run entirely before any other code runs (and can modify data the function manipulates). This differs from C, for instance, where if a function runs in a thread, it may be stopped at any point by the runtime system to run some other code in another thread.
For example, consider this example:
const promise = Promise.resolve();
let i = 0;
promise.then(() => {
i += 1;
console.log(i);
});
promise.then(() => {
i += 1;
console.log(i);
});
In this example, we create an already-resolved promise, which means any callback attached to it will be immediately scheduled as jobs. The two callbacks seem to cause a race condition, but actually, the output is fully predictable: 1
and 2
will be logged in order. This is because each job runs to completion before the next one is executed, so the overall order is always i += 1; console.log(i); i += 1; console.log(i);
and never i += 1; i += 1; console.log(i); console.log(i);
.
A downside of this model is that if a job takes too long to complete, the web application is unable to process user interactions like click or scroll. The browser mitigates this with the "a script is taking too long to run" dialog. A good practice to follow is to make job processing short and, if possible, cut down one job into several jobs.
Never blocking
Another important guarantee offered by the event loop model is that JavaScript execution is never blocking. Handling I/O is typically performed via events and callbacks, so when the application is waiting for an IndexedDB query to return or a fetch()
request to return, it can still process other things like user input. The code that executes after the completion of an asynchronous action is always provided as a callback function (for example, the promise then()
handler, the callback function in setTimeout()
, or the event handler), which defines a job to be added to the job queue once the action completes.
Of course, the guarantee of "never-blocking" requires the platform API to be inherently asynchronous, but some legacy exceptions exist like alert()
or synchronous XHR. It is considered good practice to avoid them to ensure the responsiveness of the application.
Agent clusters and memory sharing
Multiple agents can communicate via memory sharing, forming an agent cluster. Agents are within the same cluster if and only if they can share memory. There is no built-in mechanism for two agent clusters to exchange any information, so they can be regarded as completely isolated execution models.
When creating an agent (such as by spawning a worker), there are some criteria for whether it's in the same cluster as the current agent, or a new cluster is created. For example, the following pairs of global objects are each within the same agent cluster, and thus can share memory with each other:
- A
Window
object and a dedicated worker that it created. - A worker (of any type) and a dedicated worker it created.
- A
Window
object A and theWindow
object of a same-originiframe
element that A created. - A
Window
object and a same-originWindow
object that opened it. - A
Window
object and a worklet that it created.
The following pairs of global objects are not within the same agent cluster, and thus cannot share memory:
- A
Window
object and a shared worker it created. - A worker (of any type) and a shared worker it created.
- A
Window
object and a service worker it created. - A
Window
object A and theWindow
object of aniframe
element that A created that cannot be same origin-domain with A. - Any two
Window
objects with no opener or ancestor relationship. This holds even if the twoWindow
objects are same origin.
For the exact algorithm, check the HTML specification.
Cross-agent communication and memory model
As aforementioned, agents communicate via memory sharing. On the web, memory is shared via the postMessage()
method. The using web workers guide provides an overview of this. Typically, data is passed by value only (via structured cloning), and therefore does not involve any concurrency complications. To share memory, one must post a SharedArrayBuffer
object, which can be simultaneously accessed by multiple agents. Once two agents share access to the same memory via a SharedArrayBuffer
, they can synchronize executions via the Atomics
object.
There are two ways to access shared memory: via normal memory access (which is not atomic) and via atomic memory access. The latter is sequentially consistent (which means there is a strict total ordering of events agreed upon by all agents in the cluster), while the former is unordered (which means no ordering exists); JavaScript does not provide operations with other ordering guarantees.
The spec provides the following guidelines for programmers working with shared memory:
We recommend programs be kept data race free, i.e., make it so that it is impossible for there to be concurrent non-atomic operations on the same memory location. Data race free programs have interleaving semantics where each step in the evaluation semantics of each agent are interleaved with each other. For data race free programs, it is not necessary to understand the details of the memory model. The details are unlikely to build intuition that will help one to better write ECMAScript.
More generally, even if a program is not data race free it may have predictable behavior, so long as atomic operations are not involved in any data races and the operations that race all have the same access size. The simplest way to arrange for atomics not to be involved in races is to ensure that different memory cells are used by atomic and non-atomic operations and that atomic accesses of different sizes are not used to access the same cells at the same time. Effectively, the program should treat shared memory as strongly typed as much as possible. One still cannot depend on the ordering and timing of non-atomic accesses that race, but if memory is treated as strongly typed the racing accesses will not "tear" (bits of their values will not be mixed).
Concurrency and ensuring forward progress
When multiple agents cooperate, the never-blocking guarantee does not always hold. An agent can become blocked, or paused, while waiting for another agent to perform some action. This is different from waiting on a promise in the same agent, because it halts the entire agent and does not allow any other code to run in the meantime—in other words, it cannot make forward progress.
To prevent deadlocks, there are some strong restrictions on when and which agents can become blocked.
- Every unblocked agent with a dedicated executing thread eventually makes forward progress.
- In a set of agents that share an executing thread, one agent eventually makes forward progress.
- An agent does not cause another agent to become blocked except via explicit APIs that provide blocking.
- Only certain agents can be blocked. On the web, this includes dedicated workers and shared workers, but not similar-origin windows or service workers.
The agent cluster ensures some level of integrity over the activeness of its agents, in the case of external pauses or terminations:
- An agent may be paused or resumed without its knowledge or cooperation. For example, navigating away from a window may suspend code execution but preserve its state. However, an agent cluster is not allowed to be partially deactivated, to avoid an agent starving because another agent has been deactivated. For example, shared workers are never in the same agent cluster as the creator window or other dedicated workers. This is because a shared worker's lifetime is independent of documents: if a document is deactivated while its dedicated worker holds a lock, the shared worker is blocked from acquiring the lock until the dedicated worker is reactivated, if ever. Meanwhile other workers trying to access the shared worker from other windows will starve.
- Similarly, an agent may be terminated by factors external to the cluster. For example, operating systems or users killing a browser process, or the browser force-terminating one agent because it's using too many resources. In this case, all the agents in the cluster get terminated. (The spec also allows a second strategy, which is an API that allows at least one remaining member of the cluster to identify the termination and the agent that was terminated, but this is not implemented on the web.)
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification |
| ECMAScript® 2026 Language Specification |
| HTML |
See also
- Event loops in the HTML standard
- What is the Event Loop? in the Node.js docs