Dataset Preview
Duplicate
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code:   DatasetGenerationError
Exception:    IndexError
Message:      list index out of range
Traceback:    Traceback (most recent call last):
                File "/usr/local/lib/python3.12/site-packages/datasets/builder.py", line 1898, in _prepare_split_single
                  original_shard_lengths[original_shard_id] += len(table)
                  ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
              IndexError: list index out of range
              
              The above exception was the direct cause of the following exception:
              
              Traceback (most recent call last):
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1347, in compute_config_parquet_and_info_response
                  parquet_operations = convert_to_parquet(builder)
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 980, in convert_to_parquet
                  builder.download_and_prepare(
                File "/usr/local/lib/python3.12/site-packages/datasets/builder.py", line 884, in download_and_prepare
                  self._download_and_prepare(
                File "/usr/local/lib/python3.12/site-packages/datasets/builder.py", line 947, in _download_and_prepare
                  self._prepare_split(split_generator, **prepare_split_kwargs)
                File "/usr/local/lib/python3.12/site-packages/datasets/builder.py", line 1736, in _prepare_split
                  for job_id, done, content in self._prepare_split_single(
                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.12/site-packages/datasets/builder.py", line 1919, in _prepare_split_single
                  raise DatasetGenerationError("An error occurred while generating the dataset") from e
              datasets.exceptions.DatasetGenerationError: An error occurred while generating the dataset

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

url
string
title
string
content
string
code_snippets
list
language
string
source
string
token_count
int64
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse/contributors.txt
null
# 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
[]
JavaScript
mdn
142
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Symbol.hasInstance
Function.prototype[Symbol.hasInstance]()
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% |
[ "func[Symbol.hasInstance](value)\n", "class Foo {}\nconst foo = new Foo();\nconsole.log(foo instanceof Foo === Foo[Symbol.hasInstance](foo)); // true\n", "class Foo {\n static [Symbol.hasInstance](value) {\n // A custom implementation\n return false;\n }\n}\n\nconst foo = new Foo();\nconsole.log(foo instanceof Foo); // false\nconsole.log(Function.prototype[Symbol.hasInstance].call(Foo, foo)); // true\n" ]
JavaScript
mdn
752
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/formatToParts
Intl.ListFormat.prototype.formatToParts()
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 |
[ "const vehicles = [\"Motorcycle\", \"Bus\", \"Car\"];\n\nconst formatterEn = new Intl.ListFormat(\"en\", {\n style: \"long\",\n type: \"conjunction\",\n});\n\nconst formatterFr = new Intl.ListFormat(\"fr\", {\n style: \"long\",\n type: \"conjunction\",\n});\n\nconst partValuesEn = formatterEn.formatToParts(vehicles).map((p) => p.value);\nconst partValuesFr = formatterFr.formatToParts(vehicles).map((p) => p.value);\n\nconsole.log(partValuesEn);\n// Expected output: \"[\"Motorcycle\", \", \", \"Bus\", \", and \", \"Car\"]\"\nconsole.log(partValuesFr);\n// Expected output: \"[\"Motorcycle\", \", \", \"Bus\", \" et \", \"Car\"]\"\n", "formatToParts(list)\n", "const fruits = [\"Apple\", \"Orange\", \"Pineapple\"];\nconst myListFormat = new Intl.ListFormat(\"en-GB\", {\n style: \"long\",\n type: \"conjunction\",\n});\n\nconsole.table(myListFormat.formatToParts(fruits));\n// [\n// { \"type\": \"element\", \"value\": \"Apple\" },\n// { \"type\": \"literal\", \"value\": \", \" },\n// { \"type\": \"element\", \"value\": \"Orange\" },\n// { \"type\": \"literal\", \"value\": \" and \" },\n// { \"type\": \"element\", \"value\": \"Pineapple\" }\n// ]\n" ]
JavaScript
mdn
795
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
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 |
[ "const event = new Date(\"05 October 2011 14:48 UTC\");\nconsole.log(event.toString());\n// Expected output: \"Wed Oct 05 2011 16:48:00 GMT+0200 (CEST)\"\n// Note: your timezone may vary\n\nconsole.log(event.toISOString());\n// Expected output: \"2011-10-05T14:48:00.000Z\"\n", "toISOString()\n", "const d = new Date(0);\n\nconsole.log(d.toISOString()); // \"1970-01-01T00:00:00.000Z\"\n" ]
JavaScript
mdn
433
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction_assignment
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 |
[ "let a = 2;\n\nconsole.log((a -= 3));\n// Expected output: -1\n\nconsole.log((a -= \"Hello\"));\n// Expected output: NaN\n", "x -= y\n", "let bar = 5;\n\nbar -= 2; // 3\n", "bar -= \"foo\"; // NaN\n", "let foo = 3n;\nfoo -= 2n; // 1n\nfoo -= 1; // TypeError: Cannot mix BigInt and other types, use explicit conversions\n" ]
JavaScript
mdn
312
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat
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 |
[ "const number = 123456.789;\n\nconsole.log(\n new Intl.NumberFormat(\"de-DE\", { style: \"currency\", currency: \"EUR\" }).format(\n number,\n ),\n);\n// Expected output: \"123.456,79 €\"\n\n// The Japanese yen doesn't use a minor unit\nconsole.log(\n new Intl.NumberFormat(\"ja-JP\", { style: \"currency\", currency: \"JPY\" }).format(\n number,\n ),\n);\n// Expected output: \"¥123,457\"\n\n// Limit to three significant digits\nconsole.log(\n new Intl.NumberFormat(\"en-IN\", { maximumSignificantDigits: 3 }).format(\n number,\n ),\n);\n// Expected output: \"1,23,000\"\n", "new Intl.NumberFormat()\nnew Intl.NumberFormat(locales)\nnew Intl.NumberFormat(locales, options)\n\nIntl.NumberFormat()\nIntl.NumberFormat(locales)\nIntl.NumberFormat(locales, options)\n", "const formatter = Intl.NumberFormat.call(\n { __proto__: Intl.NumberFormat.prototype },\n \"en-US\",\n { notation: \"scientific\" },\n);\nconsole.log(Object.getOwnPropertyDescriptors(formatter));\n// {\n// [Symbol(IntlLegacyConstructedSymbol)]: {\n// value: NumberFormat [Intl.NumberFormat] {},\n// writable: false,\n// enumerable: false,\n// configurable: false\n// }\n// }\n", "const amount = 3500;\n\nconsole.log(new Intl.NumberFormat().format(amount));\n// '3,500' if in US English locale\n", "const amount = 3500;\n\nnew Intl.NumberFormat(\"en-US\", {\n style: \"decimal\",\n}).format(amount); // '3,500'\nnew Intl.NumberFormat(\"en-US\", {\n style: \"percent\",\n}).format(amount); // '350,000%'\n", "const amount = 3500;\n\nnew Intl.NumberFormat(\"en-US\", {\n style: \"unit\",\n unit: \"liter\",\n}).format(amount); // '3,500 L'\n\nnew Intl.NumberFormat(\"en-US\", {\n style: \"unit\",\n unit: \"liter\",\n unitDisplay: \"long\",\n}).format(amount); // '3,500 liters'\n", "const amount = -3500;\nnew Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n}).format(amount); // '-$3,500.00'\n\nnew Intl.NumberFormat(\"bn\", {\n style: \"currency\",\n currency: \"USD\",\n currencyDisplay: \"name\",\n}).format(amount); // '-3,500.00 US dollars'\n\nnew Intl.NumberFormat(\"bn\", {\n style: \"currency\",\n currency: \"USD\",\n currencySign: \"accounting\",\n}).format(amount); // '($3,500.00)'\n", "new Intl.NumberFormat(\"en-US\", {\n notation: \"scientific\",\n}).format(987654321);\n// 9.877E8\n\nnew Intl.NumberFormat(\"pt-PT\", {\n notation: \"scientific\",\n}).format(987654321);\n// 9,877E8\n\nnew Intl.NumberFormat(\"en-GB\", {\n notation: \"engineering\",\n}).format(987654321);\n// 987.654E6\n\nnew Intl.NumberFormat(\"de\", {\n notation: \"engineering\",\n}).format(987654321);\n// 987,654E6\n\nnew Intl.NumberFormat(\"zh-CN\", {\n notation: \"compact\",\n}).format(987654321);\n// 9.9亿\n\nnew Intl.NumberFormat(\"fr\", {\n notation: \"compact\",\n compactDisplay: \"long\",\n}).format(987654321);\n// 988 millions\n\nnew Intl.NumberFormat(\"en-GB\", {\n notation: \"compact\",\n compactDisplay: \"short\",\n}).format(987654321);\n// 988M\n", "new Intl.NumberFormat(\"en-US\", {\n style: \"percent\",\n signDisplay: \"exceptZero\",\n}).format(0.55);\n// '+55%'\n", "new Intl.NumberFormat(\"bn\", {\n style: \"currency\",\n currency: \"USD\",\n currencySign: \"accounting\",\n signDisplay: \"always\",\n}).format(-3500);\n// '($3,500.00)'\n", "// Formatting adds zeros to display minimum integers and fractions\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n minimumIntegerDigits: 3,\n minimumFractionDigits: 4,\n }).format(4.33),\n);\n// \"004.3300\"\n", "// Display value shortened to maximum number of digits\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n maximumFractionDigits: 2,\n }).format(4.33145),\n);\n// \"4.33\"\n", "// Minimum fractions have no effect if value is higher precision.\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n minimumFractionDigits: 2,\n }).format(4.33145),\n);\n// \"4.331\"\n", "console.log(\n new Intl.NumberFormat(\"en\", {\n maximumFractionDigits: 2,\n }).resolvedOptions(),\n);\n// {\n// …\n// minimumIntegerDigits: 1,\n// minimumFractionDigits: 0,\n// maximumFractionDigits: 2,\n// …\n// }\n\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n minimumFractionDigits: 2,\n }).resolvedOptions(),\n);\n// {\n// …\n// minimumIntegerDigits: 1,\n// minimumFractionDigits: 2,\n// maximumFractionDigits: 3,\n// …\n// }\n", "// Display 5 significant digits\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n maximumSignificantDigits: 5,\n }).format(54.33145),\n);\n// \"54.331\"\n\n// Max 2 significant digits\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n maximumSignificantDigits: 2,\n }).format(54.33145),\n);\n// \"54\"\n\n// Max 1 significant digits\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n maximumSignificantDigits: 1,\n }).format(54.33145),\n);\n// \"50\"\n", "// Minimum 10 significant digits\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n minimumSignificantDigits: 10,\n }).format(54.33145),\n);\n// \"54.33145000\"\n", "console.log(\n new Intl.NumberFormat(\"en\", {\n maximumFractionDigits: 3,\n }).format(4.33145),\n);\n// \"4.331\"\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n maximumSignificantDigits: 2,\n }).format(4.33145),\n);\n// \"4.3\"\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n maximumFractionDigits: 3,\n maximumSignificantDigits: 2,\n }).format(4.33145),\n);\n// \"4.3\"\n", "console.log(\n new Intl.NumberFormat(\"en\", {\n maximumFractionDigits: 3,\n maximumSignificantDigits: 2,\n }).resolvedOptions(),\n);\n// {\n// …\n// minimumIntegerDigits: 1,\n// minimumSignificantDigits: 1,\n// maximumSignificantDigits: 2,\n// …\n// }\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n maximumFractionDigits: 3,\n minimumSignificantDigits: 2,\n }).resolvedOptions(),\n);\n// {\n// …\n// minimumIntegerDigits: 1,\n// minimumSignificantDigits: 2,\n// maximumSignificantDigits: 21,\n// …\n// }\n", "const maxFracNF = new Intl.NumberFormat(\"en\", {\n maximumFractionDigits: 3,\n});\nconsole.log(`maximumFractionDigits:3 - ${maxFracNF.format(1.23456)}`);\n// \"maximumFractionDigits:2 - 1.235\"\n\nconst maxSigNS = new Intl.NumberFormat(\"en\", {\n maximumSignificantDigits: 3,\n});\nconsole.log(`maximumSignificantDigits:3 - ${maxSigNS.format(1.23456)}`);\n// \"maximumSignificantDigits:3 - 1.23\"\n\nconst bothAuto = new Intl.NumberFormat(\"en\", {\n maximumSignificantDigits: 3,\n maximumFractionDigits: 3,\n});\nconsole.log(`auto - ${bothAuto.format(1.23456)}`);\n// \"auto - 1.23\"\n\nconst bothLess = new Intl.NumberFormat(\"en\", {\n roundingPriority: \"lessPrecision\",\n maximumSignificantDigits: 3,\n maximumFractionDigits: 3,\n});\nconsole.log(`lessPrecision - ${bothLess.format(1.23456)}`);\n// \"lessPrecision - 1.23\"\n\nconst bothMore = new Intl.NumberFormat(\"en\", {\n roundingPriority: \"morePrecision\",\n maximumSignificantDigits: 3,\n maximumFractionDigits: 3,\n});\nconsole.log(`morePrecision - ${bothMore.format(1.23456)}`);\n// \"morePrecision - 1.235\"\n", "const bothLess = new Intl.NumberFormat(\"en\", {\n roundingPriority: \"lessPrecision\",\n minimumFractionDigits: 2,\n minimumSignificantDigits: 2,\n});\nconsole.log(`lessPrecision - ${bothLess.format(1)}`);\n// \"lessPrecision - 1.00\"\n\nconst bothMore = new Intl.NumberFormat(\"en\", {\n roundingPriority: \"morePrecision\",\n minimumFractionDigits: 2,\n minimumSignificantDigits: 2,\n});\nconsole.log(`morePrecision - ${bothMore.format(1)}`);\n// \"morePrecision - 1.0\"\n", "// Value below half-increment: round down.\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n maximumSignificantDigits: 2,\n }).format(2.23),\n);\n// \"2.2\"\n\n// Value on or above half-increment: round up.\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n maximumSignificantDigits: 2,\n }).format(2.25),\n);\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n maximumSignificantDigits: 2,\n }).format(2.28),\n);\n// \"2.3\"\n// \"2.3\"\n", "// Value below half-increment: round down.\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n maximumSignificantDigits: 2,\n }).format(-2.23),\n);\n// \"-2.2\"\n\n// Value on or above half-increment: round up.\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n maximumSignificantDigits: 2,\n }).format(-2.25),\n);\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n maximumSignificantDigits: 2,\n }).format(-2.28),\n);\n// \"-2.3\"\n// \"-2.3\"\n", "const nf = new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n maximumFractionDigits: 2,\n roundingIncrement: 5,\n});\n\nconsole.log(nf.format(11.29)); // \"$11.30\"\nconsole.log(nf.format(11.25)); // \"$11.25\"\nconsole.log(nf.format(11.22)); // \"$11.20\"\n", "const nf = new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n maximumFractionDigits: 2,\n roundingIncrement: 10,\n});\n\nconsole.log(nf.format(11.29)); // \"$11.30\"\nconsole.log(nf.format(11.25)); // \"$11.30\"\nconsole.log(nf.format(11.22)); // \"$11.20\"\n", "const nf = new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n maximumFractionDigits: 2,\n roundingIncrement: 5,\n roundingMode: \"halfCeil\",\n});\n\nconsole.log(nf.format(11.21)); // \"$11.20\"\nconsole.log(nf.format(11.22)); // \"$11.20\"\nconsole.log(nf.format(11.224)); // \"$11.20\"\nconsole.log(nf.format(11.225)); // \"$11.25\"\nconsole.log(nf.format(11.23)); // \"$11.25\"\n" ]
JavaScript
mdn
9,880
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat
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 |
[ "const duration = {\n hours: 1,\n minutes: 46,\n seconds: 40,\n};\n\n// With style set to \"long\" and locale \"fr-FR\"\nnew Intl.DurationFormat(\"fr-FR\", { style: \"long\" }).format(duration);\n// \"1 heure, 46 minutes et 40 secondes\"\n\n// With style set to \"short\" and locale \"en\"\nnew Intl.DurationFormat(\"en\", { style: \"short\" }).format(duration);\n// \"1 hr, 46 min and 40 sec\"\n\n// With style set to \"narrow\" and locale \"pt\"\nnew Intl.DurationFormat(\"pt\", { style: \"narrow\" }).format(duration);\n// \"1 h 46 min 40 s\"\n" ]
JavaScript
mdn
697
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString
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 |
[ "function hexColor(c) {\n if (c < 256) {\n return Math.abs(c).toString(16);\n }\n return 0;\n}\n\nconsole.log(hexColor(233));\n// Expected output: \"e9\"\n\nconsole.log(hexColor(\"11\"));\n// Expected output: \"b\"\n", "toString()\ntoString(radix)\n", "console.log((10 ** 21.5).toString()); // \"3.1622776601683794e+21\"\nconsole.log((10 ** 21.5).toString(8)); // \"526665530627250154000000\"\n", "console.log((1000000000000000128).toString()); // \"1000000000000000100\"\nconsole.log(1000000000000000100 === 1000000000000000128); // true\n", "Number.prototype.toString = () => \"Overridden\";\nconsole.log(`${1}`); // \"1\"\nconsole.log(`${new Number(1)}`); // \"Overridden\"\n", "const count = 10;\nconsole.log(count.toString()); // \"10\"\n\nconsole.log((17).toString()); // \"17\"\nconsole.log((17.2).toString()); // \"17.2\"\n\nconst x = 6;\nconsole.log(x.toString(2)); // \"110\"\nconsole.log((254).toString(16)); // \"fe\"\nconsole.log((-10).toString(2)); // \"-1010\"\nconsole.log((-0xff).toString(2)); // \"-11111111\"\n", "const hex = \"CAFEBABE\";\nconst bin = parseInt(hex, 16).toString(2); // \"11001010111111101011101010111110\"\n" ]
JavaScript
mdn
1,506
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor
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 |
[ "const o1 = {};\no1.constructor === Object; // true\n\nconst o2 = new Object();\no2.constructor === Object; // true\n\nconst a1 = [];\na1.constructor === Array; // true\n\nconst a2 = new Array();\na2.constructor === Array; // true\n\nconst n = 3;\nn.constructor === Number; // true\n", "const o = new TypeError(); // Inheritance: TypeError -> Error -> Object\nconst proto = Object.getPrototypeOf;\n\nObject.hasOwn(o, \"constructor\"); // false\nproto(o).constructor === TypeError; // true\nproto(proto(o)).constructor === Error; // true\nproto(proto(proto(o))).constructor === Object; // true\n", "function Tree(name) {\n this.name = name;\n}\n\nconst theTree = new Tree(\"Redwood\");\nconsole.log(`theTree.constructor is ${theTree.constructor}`);\n", "const arr = [];\narr.constructor = String;\narr.constructor === String; // true\narr instanceof String; // false\narr instanceof Array; // true\n\nconst foo = new Foo();\nfoo.constructor = \"bar\";\nfoo.constructor === \"bar\"; // true\n\n// etc.\n", "const arr = [];\nObject.hasOwn(arr, \"constructor\"); // false\nObject.hasOwn(Object.getPrototypeOf(arr), \"constructor\"); // true\n\narr.constructor = String;\nObject.hasOwn(arr, \"constructor\"); // true — the instance property shadows the one on its prototype\n", "const arr = [];\narr.constructor = String;\narr instanceof String; // false\narr instanceof Array; // true\n", "function Parent() {\n // …\n}\nParent.prototype.parentMethod = function () {};\n\nfunction Child() {\n Parent.call(this); // Make sure everything is initialized properly\n}\n// Pointing the [[Prototype]] of Child.prototype to Parent.prototype\nChild.prototype = Object.create(Parent.prototype);\n", "function Parent() {\n // …\n}\nfunction CreatedConstructor() {\n Parent.call(this);\n}\n\nCreatedConstructor.prototype = Object.create(Parent.prototype);\n\nCreatedConstructor.prototype.create = function () {\n return new this.constructor();\n};\n\nnew CreatedConstructor().create().create(); // TypeError: new CreatedConstructor().create().create is undefined, since constructor === Parent\n", "function Parent() {\n // …\n}\nfunction CreatedConstructor() {\n // …\n}\n\nCreatedConstructor.prototype = Object.create(Parent.prototype, {\n // Return original constructor to Child\n constructor: {\n value: CreatedConstructor,\n enumerable: false, // Make it non-enumerable, so it won't appear in `for...in` loop\n writable: true,\n configurable: true,\n },\n});\n\nCreatedConstructor.prototype.create = function () {\n return new this.constructor();\n};\n\nnew CreatedConstructor().create().create(); // it's pretty fine\n", "function Parent() {\n // …\n}\nfunction CreatedConstructor() {\n // …\n}\n\nObject.setPrototypeOf(CreatedConstructor.prototype, Parent.prototype);\n\nCreatedConstructor.prototype.create = function () {\n return new this.constructor();\n};\n\nnew CreatedConstructor().create().create(); // still works without re-creating constructor property\n", "function ParentWithStatic() {}\n\nParentWithStatic.startPosition = { x: 0, y: 0 }; // Static member property\nParentWithStatic.getStartPosition = function () {\n return this.startPosition;\n};\n\nfunction Child(x, y) {\n this.position = { x, y };\n}\n\nChild.prototype = Object.create(ParentWithStatic.prototype, {\n // Return original constructor to Child\n constructor: {\n value: Child,\n enumerable: false,\n writable: true,\n configurable: true,\n },\n});\n\nChild.prototype.getOffsetByInitialPosition = function () {\n const position = this.position;\n // Using this.constructor, in hope that getStartPosition exists as a static method\n const startPosition = this.constructor.getStartPosition();\n\n return {\n offsetX: startPosition.x - position.x,\n offsetY: startPosition.y - position.y,\n };\n};\n\nnew Child(1, 1).getOffsetByInitialPosition();\n// Error: this.constructor.getStartPosition is undefined, since the\n// constructor is Child, which doesn't have the getStartPosition static method\n", "// …\nObject.assign(Child, ParentWithStatic); // Notice that we assign it before we create() a prototype below\nChild.prototype = Object.create(ParentWithStatic.prototype, {\n // Return original constructor to Child\n constructor: {\n value: Child,\n enumerable: false,\n writable: true,\n configurable: true,\n },\n});\n// …\n", "function ParentWithStatic() {}\n\nParentWithStatic.startPosition = { x: 0, y: 0 }; // Static member property\nParentWithStatic.getStartPosition = function () {\n return this.startPosition;\n};\n\nfunction Child(x, y) {\n this.position = { x, y };\n}\n\n// Properly create inheritance!\nObject.setPrototypeOf(Child.prototype, ParentWithStatic.prototype);\nObject.setPrototypeOf(Child, ParentWithStatic);\n\nChild.prototype.getOffsetByInitialPosition = function () {\n const position = this.position;\n const startPosition = this.constructor.getStartPosition();\n\n return {\n offsetX: startPosition.x - position.x,\n offsetY: startPosition.y - position.y,\n };\n};\n\nconsole.log(new Child(1, 1).getOffsetByInitialPosition()); // { offsetX: -1, offsetY: -1 }\n" ]
JavaScript
mdn
3,724
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Symbol.toPrimitive
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% |
[ "// Depending on timezone, your results will vary\nconst date = new Date(\"20 December 2019 14:48\");\n\nconsole.log(date[Symbol.toPrimitive](\"string\"));\n// Expected output: \"Fri Dec 20 2019 14:48:00 GMT+0530 (India Standard Time)\"\n\nconsole.log(date[Symbol.toPrimitive](\"number\"));\n// Expected output: 1576833480000\n", "date[Symbol.toPrimitive](hint)\n", "const d = new Date(0); // 1970-01-01T00:00:00.000Z\n\nd[Symbol.toPrimitive](\"string\"); // \"Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)\"\nd[Symbol.toPrimitive](\"number\"); // 0\nd[Symbol.toPrimitive](\"default\"); // \"Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)\"\n" ]
JavaScript
mdn
832
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Duration/seconds
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
[ "const d1 = Temporal.Duration.from({ minutes: 1, seconds: 30 });\nconst d2 = Temporal.Duration.from({ minutes: -1, seconds: -30 });\nconst d3 = Temporal.Duration.from({ minutes: 1 });\nconst d4 = Temporal.Duration.from({ seconds: 60 });\n\nconsole.log(d1.seconds); // 30\nconsole.log(d2.seconds); // -30\nconsole.log(d3.seconds); // 0\nconsole.log(d4.seconds); // 60\n\n// Balance d4\nconst d4Balanced = d4.round({ largestUnit: \"minutes\" });\nconsole.log(d4Balanced.seconds); // 0\nconsole.log(d4Balanced.minutes); // 1\n" ]
JavaScript
mdn
555
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
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()
[ "const date = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));\n// Results below assume UTC timezone - your results may vary\n\n// Specify default date formatting for language (locale)\nconsole.log(new Intl.DateTimeFormat(\"en-US\").format(date));\n// Expected output: \"12/20/2020\"\n\n// Specify default date formatting for language with a fallback language (in this case Indonesian)\nconsole.log(new Intl.DateTimeFormat([\"ban\", \"id\"]).format(date));\n// Expected output: \"20/12/2020\"\n\n// Specify date and time format using \"style\" options (i.e. full, long, medium, short)\nconsole.log(\n new Intl.DateTimeFormat(\"en-GB\", {\n dateStyle: \"full\",\n timeStyle: \"long\",\n timeZone: \"Australia/Sydney\",\n }).format(date),\n);\n// Expected output: \"Sunday, 20 December 2020 at 14:23:16 GMT+11\"\n", "const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n\n// toLocaleString without arguments depends on the implementation,\n// the default locale, and the default time zone\nconsole.log(new Intl.DateTimeFormat().format(date));\n// \"12/19/2012\" if run with en-US locale (language) and time zone America/Los_Angeles (UTC-0800)\n", "const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n\n// Results below use the time zone of America/Los_Angeles (UTC-0800, Pacific Standard Time)\n\n// US English uses month-day-year order\nconsole.log(new Intl.DateTimeFormat(\"en-US\").format(date));\n// \"12/19/2012\"\n\n// British English uses day-month-year order\nconsole.log(new Intl.DateTimeFormat(\"en-GB\").format(date));\n// \"19/12/2012\"\n\n// Korean uses year-month-day order\nconsole.log(new Intl.DateTimeFormat(\"ko-KR\").format(date));\n// \"2012. 12. 19.\"\n\n// Arabic in most Arabic speaking countries uses real Arabic digits\nconsole.log(new Intl.DateTimeFormat(\"ar-EG\").format(date));\n// \"١٩‏/١٢‏/٢٠١٢\"\n\n// for Japanese, applications may want to use the Japanese calendar,\n// where 2012 was the year 24 of the Heisei era\nconsole.log(new Intl.DateTimeFormat(\"ja-JP-u-ca-japanese\").format(date));\n// \"24/12/19\"\n\n// when requesting a language that may not be supported, such as\n// Balinese, include a fallback language, in this case Indonesian\nconsole.log(new Intl.DateTimeFormat([\"ban\", \"id\"]).format(date));\n// \"19/12/2012\"\n", "const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200));\n\n// request a weekday along with a long date\nlet options = {\n weekday: \"long\",\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n};\nconsole.log(new Intl.DateTimeFormat(\"de-DE\", options).format(date));\n// \"Donnerstag, 20. Dezember 2012\"\n\n// an application may want to use UTC and make that visible\noptions.timeZone = \"UTC\";\noptions.timeZoneName = \"short\";\nconsole.log(new Intl.DateTimeFormat(\"en-US\", options).format(date));\n// \"Thursday, December 20, 2012, GMT\"\n\n// sometimes you want to be more precise\noptions = {\n hour: \"numeric\",\n minute: \"numeric\",\n second: \"numeric\",\n timeZone: \"Australia/Sydney\",\n timeZoneName: \"short\",\n};\nconsole.log(new Intl.DateTimeFormat(\"en-AU\", options).format(date));\n// \"2:00:00 pm AEDT\"\n\n// sometimes you want to be very precise\noptions.fractionalSecondDigits = 3; // number digits for fraction-of-seconds\nconsole.log(new Intl.DateTimeFormat(\"en-AU\", options).format(date));\n// \"2:00:00.200 pm AEDT\"\n\n// sometimes even the US needs 24-hour time\noptions = {\n year: \"numeric\",\n month: \"numeric\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n second: \"numeric\",\n hour12: false,\n timeZone: \"America/Los_Angeles\",\n};\nconsole.log(new Intl.DateTimeFormat(\"en-US\", options).format(date));\n// \"12/19/2012, 19:00:00\"\n\n// to specify options but use the browser's default locale, use undefined\nconsole.log(new Intl.DateTimeFormat(undefined, options).format(date));\n// \"12/19/2012, 19:00:00\"\n\n// sometimes it's helpful to include the period of the day\noptions = { hour: \"numeric\", dayPeriod: \"short\" };\nconsole.log(new Intl.DateTimeFormat(\"en-US\", options).format(date));\n// 10 at night\n", "const options = { calendar: \"chinese\", numberingSystem: \"arab\" };\nconst dateFormat = new Intl.DateTimeFormat(undefined, options);\nconst usedOptions = dateFormat.resolvedOptions();\n\nconsole.log(usedOptions.calendar);\n// \"chinese\"\n\nconsole.log(usedOptions.numberingSystem);\n// \"arab\"\n\nconsole.log(usedOptions.timeZone);\n// \"America/New_York\" (the users default timezone)\n" ]
JavaScript
mdn
2,914
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Execution_model
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
[ "function foo(b) {\n const a = 10;\n return a + b + 11;\n}\n\nfunction bar(x) {\n const y = 3;\n return foo(x * y);\n}\n\nconst baz = bar(7); // assigns 42 to baz\n", "function* gen() {\n console.log(1);\n yield;\n console.log(2);\n}\n\nconst g = gen();\ng.next(); // logs 1\ng.next(); // logs 2\n", "function f() {\n return g();\n}\n", "function factorial(n, acc = 1) {\n if (n <= 1) return acc;\n return factorial(n - 1, n * acc);\n}\n", "let f;\n{\n let x = 10;\n f = () => x;\n}\nconsole.log(f()); // logs 10\n", "const promise = Promise.resolve();\nlet i = 0;\npromise.then(() => {\n i += 1;\n console.log(i);\n});\npromise.then(() => {\n i += 1;\n console.log(i);\n});\n" ]
JavaScript
mdn
5,176
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/supportedValuesOf
Intl.supportedValuesOf()
Intl.supportedValuesOf() Baseline Widely available This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2022. The Intl.supportedValuesOf() static method returns an array containing the supported calendar, collation, currency, numbering systems, or unit values supported by the implementation. Duplicates are omitted and the array is sorted in ascending lexicographical order (or more precisely, using Array.prototype.sort() with an undefined compare function). The method can be used to feature-test whether values are supported in a particular implementation and download a polyfill only if necessary. It can also be used to build UIs that allow users to select their preferred localized values, for example when the UI is created from WebGL or server-side. This method is locale-unaware: it is possible that certain identifiers are only supported or preferred in certain locales. If you want to determine the preferred values for a specific locale, you should use the Intl.Locale object, such as Intl.Locale.prototype.getCalendars() . Try it console.log(Intl.supportedValuesOf("calendar")); console.log(Intl.supportedValuesOf("collation")); console.log(Intl.supportedValuesOf("currency")); console.log(Intl.supportedValuesOf("numberingSystem")); console.log(Intl.supportedValuesOf("timeZone")); console.log(Intl.supportedValuesOf("unit")); // Expected output: Array ['key'] (for each key) try { Intl.supportedValuesOf("someInvalidKey"); } catch (err) { console.log(err.toString()); // Expected output: RangeError: invalid key: "someInvalidKey" } Syntax Intl.supportedValuesOf(key) Parameters key - A key string indicating the category of values to be returned. This is one of: "calendar" : see supported calendar types"collation" : see supported collation types"currency" : see supported currency identifiers"numberingSystem" : see supported numbering system types"timeZone" : see supported time zone identifiers"unit" : see supported unit identifiers Return value A sorted array of unique string values indicating the values supported by the implementation for the given key. The values that could be returned are listed below. Supported calendar types Below are all values that are commonly supported by browsers for the calendar key. These values can be used for the calendar option or the ca Unicode extension key when creating objects such as Intl.DateTimeFormat , as well as for creating Temporal date objects. This list is explicitly sanctioned by the ECMA-402 specification, so all implementations should be consistent. | Value | Description | |---|---| buddhist | Thai Buddhist calendar, proleptic. Month numbers, month codes, and days are the same as in the ISO 8601 calendar, but the epoch year is different. There is one era. | chinese | Traditional Chinese calendar, proleptic. Lunisolar calendar used in China based on data published by the Purple Mountain Observatory between 1900 and 2100 (which compiles with GB/T 33661-2017 between 1912 and 2100), falling back to an implementation-defined approximation outside that range. The arithmetic year is identical to gregory , and there are no eras. | coptic | Coptic calendar, proleptic. Similar solar algorithm to ethioaa and ethiopic , with one era and a different epoch year. | dangi | Traditional Korean calendar, proleptic. Lunisolar calendar using months published by the Korea Astronomy and Space Science Institute (KASI) between 1900 and 2050, falling back to an implementation-defined approximation outside that range. The arithmetic year is identical to gregory , and there are no eras. | ethioaa | Ethiopic calendar, Amete Alem, proleptic. Similar solar algorithm to coptic and ethiopic , with one era and a different epoch year. | ethiopic | Ethiopic calendar, Amete Mihret, proleptic. Similar solar algorithm to coptic and ethioaa , with two eras and a different epoch year. | gregory | Gregorian calendar, proleptic. Solar calendar almost identical to the ISO 8601 calendar, except that it does not define week numbering and it contains two eras, one before the epoch year. | hebrew | Hebrew calendar, proleptic. Civil calendar with Tishrei as the first month of the year. Lunisolar calendar with one leap month inserted after month 5. There is one era. | indian | Indian national (or Śaka) calendar, proleptic. Solar calendar with one era. | islamic-civil | Hijri calendar, proleptic, tabular/rule-based with leap year rule II (leap years 2,5,7,10,13,16,18,21,24,26,29 in the 30-year cycle (1-based numbering)) and civil epoch (Friday July 16, 622 Julian / 0622-07-19 ISO) | islamic-tbla | Hijri calendar, proleptic, tabular/rule-based with leap year rule II (leap years 2,5,7,10,13,16,18,21,24,26,29 in the 30-year cycle (1-based numbering)) and astronomical epoch (Thursday July 15, 622 Julian / 0622-07-18 ISO) | islamic-umalqura | Hijri calendar, proleptic, Umm al-Qura. Lunar calendar using KACST-calculated months from the start of 1300 AH (1882-11-12 ISO) to the end of 1600 AH (2174-11-25 ISO), falling back to islamic-civil outside that range. | iso8601 | ISO calendar (variant of the Gregorian calendar with week rules and formatting parameters made region-independent) | japanese | Japanese Imperial calendar (this calendar adds an era for each new emperor, so the output year and era for a future date may not match the input year and era when your code runs on a future engine version. Note: See the remarks below this table about dates prior to 1868-10-23 ISO.) | persian | Persian (or Solar Hijri) calendar, proleptic. There is one era. | roc | Republic of China (or Minguo) calendar, proleptic. Month numbers, month codes, and days are the same as in the ISO 8601 calendar, but the epoch year is different. There are two eras, one before the epoch year and one after. | As of October 2025, in the japanese calendar, dates prior to 1868-10-23 ISO (the start date of the year 1 Meiji) don't work as expected in browsers in two ways. First, CLDR had the wrong start date for the Meiji era, which causes calendar implementations to extend the Meiji era further to the past than it actually did. Second, the upcoming Intl era and monthCode Proposal specifies that dates prior to 1873-01-01 ISO should use Gregorian eras, but browsers have traditionally used approximations of prior Japanese eras instead. The japanese calendar was taken into use on January 1, 6 Meiji / 1873-01-01 ISO, so these problems only affect proleptic dates. The types below are specified in CLDR but do not have implementations distinct from the above calendars in browsers. | Value | Description | Notes | |---|---|---| ethiopic-amete-alem | Ethiopic calendar, Amete Alem, proleptic. | This is an alias for ethioaa and therefore is not returned by supportedValuesOf() . Use ethioaa instead. | islamic | Hijri calendar, unspecified algorithm. | As of April 2025, this is an astronomical simulation whose parameters are undocumented and that is not known to match a specific Hijri calendar variant from non-software contexts. It is specified to be canonicalized to a different calendar, usually one of islamic-umalqura , islamic-tbla , or islamic-civil , and raise a warning. | islamicc Deprecated | Civil (algorithmic) Arabic calendar. | This is an alias for islamic-civil and therefore is not returned by supportedValuesOf() . Use islamic-civil instead. | The Temporal.PlainDate.prototype.era and Temporal.PlainDate.prototype.monthCode docs provide more information about different calendars. References: - CLDR Calendar type keys - UTS 35, Dates - Islamic calendar types (CLDR design proposal) Supported collation types Below are all values that are commonly supported by browsers for the collation key. These values can be used for the collation option or the co Unicode extension key when creating objects such as Intl.Collator . | Value | Description | |---|---| compat | A previous version of the ordering, for compatibility (for Arabic) | dict | Dictionary style ordering (such as in Sinhala). Also recognized as dictionary . | emoji | Recommended ordering for emoji characters | eor | European ordering rules | phonebk | Phonebook style ordering (such as in German). Also recognized as phonebook . | phonetic | Phonetic ordering (sorting based on pronunciation; for Lingala) | pinyin | Pinyin ordering for Latin and for CJK characters (used in Chinese) | searchjl | Special collation type for Korean initial consonant search. Warning: This collation is not for sorting, even though you can only use it with Intl.Collator of usage: "sort" . | stroke | Pinyin ordering for Latin, stroke order for CJK characters (used in Chinese) | trad | Traditional style ordering (such as in Spanish). Also recognized as traditional . | unihan | Pinyin ordering for Latin, Unihan radical-stroke ordering for CJK characters (used in Chinese) | zhuyin | Pinyin ordering for Latin, zhuyin order for Bopomofo and CJK characters (used in Chinese) | The types below are specified in CLDR data, but are deprecated, are discouraged from explicit usage, and/or may not be indicated by browsers as supported for various reasons. Avoid using them: | Value | Description | Notes | |---|---|---| big5han Deprecated | Pinyin ordering for Latin, big5 charset ordering for CJK characters (used in Chinese) | Deprecated. | direct Deprecated | Binary code point order (used in Hindi) | Deprecated. | ducet | The default Unicode collation element table order | The ducet collation type is not available to the Web. | gb2312 Deprecated | Pinyin ordering for Latin, gb2312han charset ordering for CJK characters (for Chinese). Also recognized as gb2312han . | Deprecated. | reformed Deprecated | Reformed ordering (such as Swedish) | Deprecated. This is the old name for the default ordering for Swedish whose collation naming used to differ from other languages. Since this was the default, request sv instead of requesting sv-u-co-reformed . | search | Special collation type for string search | Do not use as a collation type, since in Intl.Collator , this collation is activated via the usage: "search" option. There is currently no API for substring search, so this is currently only good for filtering a list of strings by trying a full-string match of the key against each list item. | standard | Default ordering for each language, except Chinese (and, previously, Swedish) | Do not use explicitly. In general, it's unnecessary to specify this explicitly and specifying this for Swedish is problematic due to the different meaning for Swedish in the past. | References: Supported currency identifiers Currency identifiers are three-letter uppercase codes defined in ISO 4217. These values can be used for the currency option when creating objects such as Intl.NumberFormat , as well as for Intl.DisplayNames.prototype.of() . There are over 300 identifiers in common use so we won't list them. For an exhaustive list of possible identifiers, see the Wikipedia article. References: Supported numbering system types Below are all values that are commonly supported by browsers for the numberingSystem key. These values can be used for the numberingSystem option or the nu Unicode extension key when creating objects such as Intl.NumberFormat . For the rows with "digit characters", the runtime translates the digits one-by-one without extra actions. The others marked as "algorithmic" need additional algorithms to translate the digits. The higher the Unicode code point is, the newer the numbering system is and the more likely it is unsupported by all browsers. | Value | Description | Digit characters | |---|---|---| adlm | Adlam digits | 𞥐𞥑𞥒𞥓𞥔𞥕𞥖𞥗𞥘𞥙 (U+1E950 to U+1E959) | ahom | Ahom digits | 𑜰𑜱𑜲𑜳𑜴𑜵𑜶𑜷𑜸𑜹 (U+11730 to U+11739) | arab | Arabic-Indic digits | ٠١٢٣٤٥٦٧٨٩ (U+0660 to U+0669) | arabext | Extended Arabic-Indic digits | ۰۰۱۲۳۴۵۶۷۸۹ (U+06F0 to U+06F9) | armn | Armenian upper case numerals | algorithmic | armnlow | Armenian lower case numerals | algorithmic | bali | Balinese digits | ᭐᭑᭒᭓᭔᭕᭖᭗᭘᭙ (U+1B50 to U+1B59) | beng | Bengali digits | ০১২৩৪৫৬৭৮৯ (U+09E6 to U+09EF) | bhks | Bhaiksuki digits | 𑱐𑱑𑱒𑱓𑱔𑱕𑱖𑱗𑱘𑱙 (U+11C50 to U+11C59) | brah | Brahmi digits | 𑁦𑁧𑁨𑁩𑁪𑁫𑁬𑁭𑁮𑁯 (U+11066 to U+1106F) | cakm | Chakma digits | 𑄶𑄷𑄸𑄹𑄺𑄻𑄼𑄽𑄾𑄿 (U+11136 to U+1113F) | cham | Cham digits | ꩐꩑꩒꩓꩔꩕꩖꩗꩘꩙ (U+AA50 to U+AA59) | cyrl | Cyrillic numerals | algorithmic | deva | Devanagari digits | ०१२३४५६७८९ (U+0966 to U+096F) | diak | Dives Akuru digits | 𑥐𑥑𑥒𑥓𑥔𑥕𑥖𑥗𑥘𑥙 (U+11950 to U+11959) | ethi | Ethiopic numerals | algorithmic | fullwide | Full width digits | 0123456789 (U+FF10 to U+FF19) | gara | Garay digits | (U+10D40 to U+10D49) | geor | Georgian numerals | algorithmic | gong | Gunjala Gondi digits | 𑶠𑶡𑶢𑶣𑶤𑶥𑶦𑶧𑶨𑶩 (U+11DA0 to U+11DA9) | gonm | Masaram Gondi digits | 𑵐𑵑𑵒𑵓𑵔𑵕𑵖𑵗𑵘𑵙 (U+11D50 to U+11D59) | grek | Greek upper case numerals | algorithmic | greklow | Greek lower case numerals | algorithmic | gujr | Gujarati digits | ૦૧૨૩૪૫૬૭૮૯ (U+0AE6 to U+0AEF) | gukh | Gurung Khema digits | (U+16130 to U+16139) | guru | Gurmukhi digits | ੦੧੨੩੪੫੬੭੮੯ (U+0A66 to U+0A6F) | hanidays | Han-character day-of-month numbering for lunar/other traditional calendars | | hanidec | Positional decimal system using Chinese number ideographs as digits | 〇一二三四五六七八九 (U+3007, U+4E00, U+4E8C, U+4E09, U+56DB, U+4E94, U+516D, U+4E03, U+516B, U+4E5D) | hans | Simplified Chinese numerals | algorithmic | hansfin | Simplified Chinese financial numerals | algorithmic | hant | Traditional Chinese numerals | algorithmic | hantfin | Traditional Chinese financial numerals | algorithmic | hebr | Hebrew numerals | algorithmic | hmng | Pahawh Hmong digits | 𖭐𖭑𖭒𖭓𖭔𖭕𖭖𖭗𖭘𖭙 (U+16B50 to U+16B59) | hmnp | Nyiakeng Puachue Hmong digits | 𞅀𞅁𞅂𞅃𞅄𞅅𞅆𞅇𞅈𞅉 (U+1E140 to U+1E149) | java | Javanese digits | ꧐꧑꧒꧓꧔꧕꧖꧗꧘꧙ (U+A9D0 to U+A9D9) | jpan | Japanese numerals | algorithmic | jpanfin | Japanese financial numerals | algorithmic | jpanyear | Japanese first-year Gannen numbering for Japanese calendar | algorithmic | kali | Kayah Li digits | ꤀꤁꤂꤃꤄꤅꤆꤇꤈꤉ (U+A900 to U+A909) | kawi | Kawi digits | 𑽐𑽑𑽒𑽓𑽔𑽕𑽖𑽗𑽘𑽙 (U+11F50 to U+11F59) | khmr | Khmer digits | ០១២៣៤៥៦៧៨៩ (U+17E0 to U+17E9) | knda | Kannada digits | ೦೧೨೩೪೫೬೭೮೯ (U+0CE6 to U+0CEF) | krai | Kirat Rai digits | (U+16D70 to U+16D79) | lana | Tai Tham Hora (secular) digits | ᪀᪁᪂᪃᪄᪅᪆᪇᪈᪉ (U+1A80 to U+1A89) | lanatham | Tai Tham (ecclesiastical) digits | ᪐᪑᪒᪓᪔᪕᪖᪗᪘᪙ (U+1A90 to U+1A99) | laoo | Lao digits | ໐໑໒໓໔໕໖໗໘໙ (U+0ED0 to U+0ED9) | latn | Latin digits | 0123456789 (U+0030 to U+0039) | lepc | Lepcha digits | ᱀᱁᱂᱃᱄᱅᱆᱇᱈᱉ (U+1C40 to U+1C49) | limb | Limbu digits | ᥆᥇᥈᥉᥊᥋᥌᥍᥎᥏ (U+1946 to U+194F) | mathbold | Mathematical bold digits | 𝟎𝟏𝟐𝟑𝟒𝟓𝟔𝟕𝟖𝟗 (U+1D7CE to U+1D7D7) | mathdbl | Mathematical double-struck digits | 𝟘𝟙𝟚𝟛𝟜𝟝𝟞𝟟𝟠𝟡 (U+1D7D8 to U+1D7E1) | mathmono | Mathematical monospace digits | 𝟶𝟷𝟸𝟹𝟺𝟻𝟼𝟽𝟾𝟿 (U+1D7F6 to U+1D7FF) | mathsanb | Mathematical sans-serif bold digits | 𝟬𝟭𝟮𝟯𝟰𝟱𝟲𝟳𝟴𝟵 (U+1D7EC to U+1D7F5) | mathsans | Mathematical sans-serif digits | 𝟢𝟣𝟤𝟥𝟦𝟧𝟨𝟩𝟪𝟫 (U+1D7E2 to U+1D7EB) | mlym | Malayalam digits | ൦൧൨൩൪൫൬൭൮൯ (U+0D66 to U+0D6F) | modi | Modi digits | 𑙐𑙑𑙒𑙓𑙔𑙕𑙖𑙗𑙘𑙙 (U+11650 to U+11659) | mong | Mongolian digits | ᠐᠑᠒᠓᠔᠕᠖᠗᠘᠙ (U+1810 to U+1819) | mroo | Mro digits | 𖩠𖩡𖩢𖩣𖩤𖩥𖩦𖩧𖩨𖩩 (U+16A60 to U+16A69) | mtei | Meetei Mayek digits | ꯰꯱꯲꯳꯴꯵꯶꯷꯸꯹ (U+ABF0 to U+ABF9) | mymr | Myanmar digits | ၀၁၂၃၄၅၆၇၈၉ (U+1040 to U+1049) | mymrepka | Myanmar Eastern Pwo Karen digits | (U+116DA to U+116E3) | mymrpao | Myanmar Pao digits | (U+116D0 to U+116D9) | mymrshan | Myanmar Shan digits | ႐႑႒႓႔႕႖႗႘႙ (U+1090 to U+1099) | mymrtlng | Myanmar Tai Laing digits | ꧰꧱꧲꧳꧴꧵꧶꧷꧸꧹ (U+A9F0 to U+A9F9) | nagm | Nag Mundari digits | 𞓰𞓱𞓲𞓳𞓴𞓵𞓶𞓷𞓸𞓹 (U+1E4F0 to U+1E4F9) | newa | Newa digits | 𑑐𑑑𑑒𑑓𑑔𑑕𑑖𑑗𑑘𑑙 (U+11450 to U+11459) | nkoo | N'Ko digits | ߀߁߂߃߄߅߆߇߈߉ (U+07C0 to U+07C9) | olck | Ol Chiki digits | ᱐᱑᱒᱓᱔᱕᱖᱗᱘᱙ (U+1C50 to U+1C59) | onao | Ol Onal digits | (U+1E5F1 to U+1E5FA) | orya | Oriya digits | ୦୧୨୩୪୫୬୭୮୯ (U+0B66 to U+0B6F) | osma | Osmanya digits | 𐒠𐒡𐒢𐒣𐒤𐒥𐒦𐒧𐒨𐒩 (U+104A0 to U+104A9) | outlined | Legacy computing outlined digits | (U+1CCF0 to U+1CCF9) | rohg | Hanifi Rohingya digits | 𐴰𐴱𐴲𐴳𐴴𐴵𐴶𐴷𐴸𐴹 (U+10D30 to U+10D39) | roman | Roman upper case numerals | algorithmic | romanlow | Roman lowercase numerals | algorithmic | saur | Saurashtra digits | ꣐꣑꣒꣓꣔꣕꣖꣗꣘꣙ (U+A8D0 to U+A8D9) | segment | Legacy computing segmented digits | 🯰🯱🯲🯳🯴🯵🯶🯷🯸🯹 (U+1FBF0 to U+1FBF9) | shrd | Sharada digits | 𑇐𑇑𑇒𑇓𑇔𑇕𑇖𑇗𑇘𑇙 (U+111D0 to U+111D9) | sind | Khudawadi digits | 𑋰𑋱𑋲𑋳𑋴𑋵𑋶𑋷𑋸𑋹 (U+112F0 to U+112F9) | sinh | Sinhala Lith digits | ෦෧෨෩෪෫෬෭෮෯ (U+0DE6 to U+0DEF) | sora | Sora_Sompeng digits | 𑃰𑃱𑃲𑃳𑃴𑃵𑃶𑃷𑃸𑃹 (U+110F0 to U+110F9) | sund | Sundanese digits | ᮰᮱᮲᮳᮴᮵᮶᮷᮸᮹ (U+1BB0 to U+1BB9) | sunu | Sunuwar digits | (U+11BF0 to U+11BF9) | takr | Takri digits | 𑛀𑛁𑛂𑛃𑛄𑛅𑛆𑛇𑛈𑛉 (U+116C0 to U+116C9) | talu | New Tai Lue digits | ᧐᧑᧒᧓᧔᧕᧖᧗᧘᧙ (U+19D0 to U+19D9) | taml | Tamil numerals | algorithmic | tamldec | Modern Tamil decimal digits | ௦௧௨௩௪௫௬௭௮௯ (U+0BE6 to U+0BEF) | telu | Telugu digits | ౦౧౨౩౪౫౬౭౮౯ (U+0C66 to U+0C6F) | thai | Thai digits | ๐๑๒๓๔๕๖๗๘๙ (U+0E50 to U+0E59) | tibt | Tibetan digits | ༠༡༢༣༤༥༦༧༨༩ (U+0F20 to U+0F29) | tirh | Tirhuta digits | 𑓐𑓑𑓒𑓓𑓔𑓕𑓖𑓗𑓘𑓙 (U+114D0 to U+114D9) | tnsa | Tangsa digits | 𖫀𖫁𖫂𖫃𖫄𖫅𖫆𖫇𖫈𖫉 (U+16AC0 to U+16AC9) | vaii | Vai digits | ꘠꘡꘢꘣꘤꘥꘦꘧꘨꘩ (U+A620 to U+A629) | wara | Warang Citi digits | 𑣠𑣡𑣢𑣣𑣤𑣥𑣦𑣧𑣨𑣩 (U+118E0 to U+118E9) | wcho | Wancho digits | 𞋰𞋱𞋲𞋳𞋴𞋵𞋶𞋷𞋸𞋹 (U+1E2F0 to U+1E2F9) | There are three special values: native , traditio , and finance , whose meanings are locale-dependent, and will be resolved to the right system depending on the locale. Therefore, the resolvedOptions() methods will never return these values, but Intl.Locale.prototype.numberingSystem will (if provided as input). References: Supported time zone identifiers Supported time zone identifiers can be used for the timeZone option when creating objects such as Intl.DateTimeFormat , as well as for creating Temporal date objects. There are over 400 identifiers in common use so we won't list them. For an exhaustive list of possible identifiers, see the Wikipedia article or the IANA time zone database. As you browse the list, note that the standardization of Temporal requires browsers to always return the primary identifier in the IANA database, which may change over time. See time zones and offsets for more information. For example, the returned array should contain "Asia/Kolkata" instead of "Asia/Calcutta" because the latter is an alias of the former and they both correspond to India; however, it should contain both "Africa/Abidjan" and "Atlantic/Reykjavik" because they are in different countries, despite the latter also being an alias of the former. References: Supported unit identifiers Below are all values that are commonly supported by browsers for the unit key. These values can be used for the unit option when creating objects such as Intl.NumberFormat . This list is a subset of the CLDR explicitly sanctioned by the ECMA-402 specification, so all implementations should be consistent. acre bit byte celsius centimeter day degree fahrenheit fluid-ounce foot gallon gigabit gigabyte gram hectare hour inch kilobit kilobyte kilogram kilometer liter megabit megabyte meter microsecond mile mile-scandinavian milliliter millimeter millisecond minute month nanosecond ounce percent petabyte pound second stone terabit terabyte week yard year When specifying units, you can also combine two units with the "-per-" separator. For example, meter-per-second or liter-per-megabyte . References: Exceptions RangeError - Thrown if an unsupported key was passed as a parameter. Examples Feature testing You can check that the method is supported by comparing to undefined : if (typeof Intl.supportedValuesOf !== "undefined") { // method is supported } Get all values for key To get the supported values for calendar you call the method with the key "calendar" . You can then iterate through the returned array as shown below: Intl.supportedValuesOf("calendar").forEach((calendar) => { // "buddhist", "chinese", "coptic", "dangi", etc. }); The other values are all obtained in the same way: Intl.supportedValuesOf("collation").forEach((collation) => { // "compat", "dict", "emoji", etc. }); Intl.supportedValuesOf("currency").forEach((currency) => { // "ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", etc. }); Intl.supportedValuesOf("numberingSystem").forEach((numberingSystem) => { // "adlm", "ahom", "arab", "arabext", "bali", etc. }); Intl.supportedValuesOf("timeZone").forEach((timeZone) => { // "Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers", etc. }); Intl.supportedValuesOf("unit").forEach((unit) => { // "acre", "bit", "byte", "celsius", "centimeter", etc. }); Invalid key throws RangeError try { Intl.supportedValuesOf("someInvalidKey"); } catch (err) { // RangeError: invalid key: "someInvalidKey" } Specifications | Specification | |---| | ECMAScript® 2026 Internationalization API Specification # sec-intl.supportedvaluesof |
[ "console.log(Intl.supportedValuesOf(\"calendar\"));\nconsole.log(Intl.supportedValuesOf(\"collation\"));\nconsole.log(Intl.supportedValuesOf(\"currency\"));\nconsole.log(Intl.supportedValuesOf(\"numberingSystem\"));\nconsole.log(Intl.supportedValuesOf(\"timeZone\"));\nconsole.log(Intl.supportedValuesOf(\"unit\"));\n// Expected output: Array ['key'] (for each key)\n\ntry {\n Intl.supportedValuesOf(\"someInvalidKey\");\n} catch (err) {\n console.log(err.toString());\n // Expected output: RangeError: invalid key: \"someInvalidKey\"\n}\n", "Intl.supportedValuesOf(key)\n", "if (typeof Intl.supportedValuesOf !== \"undefined\") {\n // method is supported\n}\n", "Intl.supportedValuesOf(\"calendar\").forEach((calendar) => {\n // \"buddhist\", \"chinese\", \"coptic\", \"dangi\", etc.\n});\n", "Intl.supportedValuesOf(\"collation\").forEach((collation) => {\n // \"compat\", \"dict\", \"emoji\", etc.\n});\n\nIntl.supportedValuesOf(\"currency\").forEach((currency) => {\n // \"ADP\", \"AED\", \"AFA\", \"AFN\", \"ALK\", \"ALL\", \"AMD\", etc.\n});\n\nIntl.supportedValuesOf(\"numberingSystem\").forEach((numberingSystem) => {\n // \"adlm\", \"ahom\", \"arab\", \"arabext\", \"bali\", etc.\n});\n\nIntl.supportedValuesOf(\"timeZone\").forEach((timeZone) => {\n // \"Africa/Abidjan\", \"Africa/Accra\", \"Africa/Addis_Ababa\", \"Africa/Algiers\", etc.\n});\n\nIntl.supportedValuesOf(\"unit\").forEach((unit) => {\n // \"acre\", \"bit\", \"byte\", \"celsius\", \"centimeter\", etc.\n});\n", "try {\n Intl.supportedValuesOf(\"someInvalidKey\");\n} catch (err) {\n // RangeError: invalid key: \"someInvalidKey\"\n}\n" ]
JavaScript
mdn
5,609
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/contributors.txt
null
# Contributors by commit history https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/pluralrules/index.md # Original Wiki contributors longlho mfuji09 fscholz sideshowbarker battaglr shvaikalesh jpmedley Tagir-A
[]
JavaScript
mdn
65
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY
Number.POSITIVE_INFINITY
Number.POSITIVE_INFINITY 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 Number.POSITIVE_INFINITY static data property represents the positive Infinity value. Try it function checkNumber(bigNumber) { if (bigNumber === Number.POSITIVE_INFINITY) { return "Process number as Infinity"; } return bigNumber; } console.log(checkNumber(Number.MAX_VALUE)); // Expected output: 1.7976931348623157e+308 console.log(checkNumber(Number.MAX_VALUE * 2)); // Expected output: "Process number as Infinity" Value The same as the value of the global Infinity property. Property attributes of Number.POSITIVE_INFINITY | | |---|---| | Writable | no | | Enumerable | no | | Configurable | no | Description The Number.POSITIVE_INFINITY value behaves slightly differently than mathematical infinity: - Any positive value, including POSITIVE_INFINITY , multiplied byPOSITIVE_INFINITY isPOSITIVE_INFINITY . - Any negative value, including NEGATIVE_INFINITY , multiplied byPOSITIVE_INFINITY isNEGATIVE_INFINITY . - Any positive number divided by POSITIVE_INFINITY is positive zero (as defined in IEEE 754). - Any negative number divided by POSITIVE_INFINITY is negative zero (as defined in IEEE 754. - Zero multiplied by POSITIVE_INFINITY isNaN . NaN multiplied byPOSITIVE_INFINITY isNaN .POSITIVE_INFINITY , divided by any negative value exceptNEGATIVE_INFINITY , isNEGATIVE_INFINITY .POSITIVE_INFINITY , divided by any positive value exceptPOSITIVE_INFINITY , isPOSITIVE_INFINITY .POSITIVE_INFINITY , divided by eitherNEGATIVE_INFINITY orPOSITIVE_INFINITY , isNaN .Number.POSITIVE_INFINITY > x is true for any number x that isn'tPOSITIVE_INFINITY . You might use the Number.POSITIVE_INFINITY property to indicate an error condition that returns a finite number in case of success. Note, however, that NaN would be more appropriate in such a case. Because POSITIVE_INFINITY is a static property of Number , you always use it as Number.POSITIVE_INFINITY , rather than as a property of a number value. Examples Using POSITIVE_INFINITY In the following example, the variable bigNumber is assigned a value that is larger than the maximum value. When the if statement executes, bigNumber has the value Infinity , so bigNumber is set to a more manageable value before continuing. let bigNumber = Number.MAX_VALUE * 2; if (bigNumber === Number.POSITIVE_INFINITY) { bigNumber = returnFinite(); } Specifications | Specification | |---| | ECMAScript® 2026 Language Specification # sec-number.positive_infinity |
[ "function checkNumber(bigNumber) {\n if (bigNumber === Number.POSITIVE_INFINITY) {\n return \"Process number as Infinity\";\n }\n return bigNumber;\n}\n\nconsole.log(checkNumber(Number.MAX_VALUE));\n// Expected output: 1.7976931348623157e+308\n\nconsole.log(checkNumber(Number.MAX_VALUE * 2));\n// Expected output: \"Process number as Infinity\"\n", "let bigNumber = Number.MAX_VALUE * 2;\n\nif (bigNumber === Number.POSITIVE_INFINITY) {\n bigNumber = returnFinite();\n}\n" ]
JavaScript
mdn
762
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
Optional chaining (?.)
Optional chaining (?.) Baseline Widely available This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2020. The optional chaining (?. ) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null , the expression short circuits and evaluates to undefined instead of throwing an error. Try it const adventurer = { name: "Alice", cat: { name: "Dinah", }, }; const dogName = adventurer.dog?.name; console.log(dogName); // Expected output: undefined console.log(adventurer.someNonExistentMethod?.()); // Expected output: undefined Syntax obj?.prop obj?.[expr] func?.(args) Description The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined ), the expression short-circuits with a return value of undefined . When used with function calls, it returns undefined if the given function does not exist. This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required. For example, consider an object obj which has a nested structure. Without optional chaining, looking up a deeply-nested subproperty requires validating the references in between, such as: const nestedProp = obj.first && obj.first.second; The value of obj.first is confirmed to be non-null (and non-undefined ) before accessing the value of obj.first.second . This prevents the error that would occur if you accessed obj.first.second directly without testing obj.first . This is an idiomatic pattern in JavaScript, but it gets verbose when the chain is long, and it's not safe. For example, if obj.first is a Falsy value that's not null or undefined , such as 0 , it would still short-circuit and make nestedProp become 0 , which may not be desirable. With the optional chaining operator (?. ), however, you don't have to explicitly test and short-circuit based on the state of obj.first before trying to access obj.first.second : const nestedProp = obj.first?.second; By using the ?. operator instead of just . , JavaScript knows to implicitly check to be sure obj.first is not null or undefined before attempting to access obj.first.second . If obj.first is null or undefined , the expression automatically short-circuits, returning undefined . This is equivalent to the following, except that the temporary variable is in fact not created: const temp = obj.first; const nestedProp = temp === null || temp === undefined ? undefined : temp.second; Optional chaining cannot be used on a non-declared root object, but can be used with a root object with value undefined . undeclaredVar?.prop; // ReferenceError: undeclaredVar is not defined Optional chaining with function calls You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device. Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found: const result = someInterface.customMethod?.(); However, if there is a property with such a name which is not a function, using ?. will still raise a TypeError exception "someInterface.customMethod is not a function". Note: If someInterface itself is null or undefined , a TypeError exception will still be raised ("someInterface is null"). If you expect that someInterface itself may be null or undefined , you have to use ?. at this position as well: someInterface?.customMethod?.() . eval?.() is the shortest way to enter indirect eval mode. Optional chaining with expressions You can also use the optional chaining operator with bracket notation, which allows passing an expression as the property name: const propName = "x"; const nestedProp = obj?.[propName]; This is particularly useful for arrays, since array indices must be accessed with square brackets. function printMagicIndex(arr) { console.log(arr?.[42]); } printMagicIndex([0, 1, 2, 3, 4, 5]); // undefined printMagicIndex(); // undefined; if not using ?., this would throw an error: "Cannot read properties of undefined (reading '42')" Invalid optional chaining It is invalid to try to assign to the result of an optional chaining expression: const object = {}; object?.property = 1; // SyntaxError: Invalid left-hand side in assignment Template literal tags cannot be an optional chain (see SyntaxError: tagged template cannot be used with optional chain): String?.raw`Hello, world!`; String.raw?.`Hello, world!`; // SyntaxError: Invalid tagged template on optional chain The constructor of new expressions cannot be an optional chain (see SyntaxError: new keyword cannot be used with an optional chain): new Intl?.DateTimeFormat(); // SyntaxError: Invalid optional chain from new expression new Map?.(); Short-circuiting When using optional chaining with expressions, if the left operand is null or undefined , the expression will not be evaluated. For instance: const potentiallyNullObj = null; let x = 0; const prop = potentiallyNullObj?.[x++]; console.log(x); // 0 as x was not incremented Subsequent property accesses will not be evaluated either. const potentiallyNullObj = null; const prop = potentiallyNullObj?.a.b; // This does not throw, because evaluation has already stopped at // the first optional chain This is equivalent to: const potentiallyNullObj = null; const prop = potentiallyNullObj === null || potentiallyNullObj === undefined ? undefined : potentiallyNullObj.a.b; However, this short-circuiting behavior only happens along one continuous "chain" of property accesses. If you group one part of the chain, then subsequent property accesses will still be evaluated. const potentiallyNullObj = null; const prop = (potentiallyNullObj?.a).b; // TypeError: Cannot read properties of undefined (reading 'b') This is equivalent to: const potentiallyNullObj = null; const temp = potentiallyNullObj?.a; const prop = temp.b; Except the temp variable isn't created. Examples Basic example This example looks for the value of the name property for the member CSS in a map when there is no such member. The result is therefore undefined . const myMap = new Map(); myMap.set("JS", { name: "Josh", desc: "I maintain things" }); const nameBar = myMap.get("CSS")?.name; Dealing with optional callbacks or event handlers If you use callbacks or fetch methods from an object with a destructuring pattern, you may have non-existent values that you cannot call as functions unless you have tested their existence. Using ?. , you can avoid this extra test: // Code written without optional chaining function doSomething(onContent, onError) { try { // Do something with the data } catch (err) { // Testing if onError really exists if (onError) { onError(err.message); } } } // Using optional chaining with function calls function doSomething(onContent, onError) { try { // Do something with the data } catch (err) { onError?.(err.message); // No exception if onError is undefined } } Stacking the optional chaining operator With nested structures, it is possible to use optional chaining multiple times: const customer = { name: "Carl", details: { age: 82, location: "Paradise Falls", // Detailed address is unknown }, }; const customerCity = customer.details?.address?.city; // This also works with optional chaining function call const customerName = customer.name?.getName?.(); // Method does not exist, customerName is undefined Combining with the nullish coalescing operator The nullish coalescing operator may be used after optional chaining in order to build a default value when none was found: function printCustomerCity(customer) { const customerCity = customer?.city ?? "Unknown city"; console.log(customerCity); } printCustomerCity({ name: "Nathan", city: "Paris", }); // "Paris" printCustomerCity({ name: "Carl", details: { age: 82 }, }); // "Unknown city" Specifications | Specification | |---| | ECMAScript® 2026 Language Specification # prod-OptionalExpression |
[ "const adventurer = {\n name: \"Alice\",\n cat: {\n name: \"Dinah\",\n },\n};\n\nconst dogName = adventurer.dog?.name;\nconsole.log(dogName);\n// Expected output: undefined\n\nconsole.log(adventurer.someNonExistentMethod?.());\n// Expected output: undefined\n", "obj?.prop\nobj?.[expr]\nfunc?.(args)\n", "const nestedProp = obj.first && obj.first.second;\n", "const nestedProp = obj.first?.second;\n", "const temp = obj.first;\nconst nestedProp =\n temp === null || temp === undefined ? undefined : temp.second;\n", "undeclaredVar?.prop; // ReferenceError: undeclaredVar is not defined\n", "const result = someInterface.customMethod?.();\n", "const propName = \"x\";\nconst nestedProp = obj?.[propName];\n", "function printMagicIndex(arr) {\n console.log(arr?.[42]);\n}\n\nprintMagicIndex([0, 1, 2, 3, 4, 5]); // undefined\nprintMagicIndex(); // undefined; if not using ?., this would throw an error: \"Cannot read properties of undefined (reading '42')\"\n", "const object = {};\nobject?.property = 1; // SyntaxError: Invalid left-hand side in assignment\n", "String?.raw`Hello, world!`;\nString.raw?.`Hello, world!`; // SyntaxError: Invalid tagged template on optional chain\n", "new Intl?.DateTimeFormat(); // SyntaxError: Invalid optional chain from new expression\nnew Map?.();\n", "const potentiallyNullObj = null;\nlet x = 0;\nconst prop = potentiallyNullObj?.[x++];\n\nconsole.log(x); // 0 as x was not incremented\n", "const potentiallyNullObj = null;\nconst prop = potentiallyNullObj?.a.b;\n// This does not throw, because evaluation has already stopped at\n// the first optional chain\n", "const potentiallyNullObj = null;\nconst prop =\n potentiallyNullObj === null || potentiallyNullObj === undefined\n ? undefined\n : potentiallyNullObj.a.b;\n", "const potentiallyNullObj = null;\nconst prop = (potentiallyNullObj?.a).b;\n// TypeError: Cannot read properties of undefined (reading 'b')\n", "const potentiallyNullObj = null;\nconst temp = potentiallyNullObj?.a;\nconst prop = temp.b;\n", "const myMap = new Map();\nmyMap.set(\"JS\", { name: \"Josh\", desc: \"I maintain things\" });\n\nconst nameBar = myMap.get(\"CSS\")?.name;\n", "// Code written without optional chaining\nfunction doSomething(onContent, onError) {\n try {\n // Do something with the data\n } catch (err) {\n // Testing if onError really exists\n if (onError) {\n onError(err.message);\n }\n }\n}\n", "// Using optional chaining with function calls\nfunction doSomething(onContent, onError) {\n try {\n // Do something with the data\n } catch (err) {\n onError?.(err.message); // No exception if onError is undefined\n }\n}\n", "const customer = {\n name: \"Carl\",\n details: {\n age: 82,\n location: \"Paradise Falls\", // Detailed address is unknown\n },\n};\nconst customerCity = customer.details?.address?.city;\n\n// This also works with optional chaining function call\nconst customerName = customer.name?.getName?.(); // Method does not exist, customerName is undefined\n", "function printCustomerCity(customer) {\n const customerCity = customer?.city ?? \"Unknown city\";\n console.log(customerCity);\n}\n\nprintCustomerCity({\n name: \"Nathan\",\n city: \"Paris\",\n}); // \"Paris\"\nprintCustomerCity({\n name: \"Carl\",\n details: { age: 82 },\n}); // \"Unknown city\"\n" ]
JavaScript
mdn
2,871
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat
Intl.DateTimeFormat() constructor
Intl.DateTimeFormat() 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.DateTimeFormat() constructor creates Intl.DateTimeFormat objects. 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" Syntax new Intl.DateTimeFormat() new Intl.DateTimeFormat(locales) new Intl.DateTimeFormat(locales, options) Intl.DateTimeFormat() Intl.DateTimeFormat(locales) Intl.DateTimeFormat(locales, options) Note: Intl.DateTimeFormat() can be called with or without new . Both create a new Intl.DateTimeFormat instance. However, there's a special behavior when it's called without new and the this value is another Intl.DateTimeFormat 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 keys are allowed: These keys 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, date-time component options, and style shortcuts. 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. calendar - The calendar to use, such as "chinese" ,"gregory" ,"persian" , and so on. For a list of supported calendar types, seeIntl.supportedValuesOf() ; the default is locale dependent. This option can also be set through theca Unicode extension key; if both are provided, thisoptions property takes precedence. 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. hour12 - Whether to use 12-hour time (as opposed to 24-hour time). Possible values are true andfalse ; the default is locale dependent. Whentrue , this option setshourCycle to either"h11" or"h12" , depending on the locale. Whenfalse , it setshourCycle to"h23" .hour12 overrides both thehc locale extension tag and thehourCycle option, should either or both of those be present. hourCycle - The hour cycle to use. Possible values are "h11" ,"h12" ,"h23" , and"h24" ; the default is inferred fromhour12 and locale. This option can also be set through thehc Unicode extension key; if both are provided, thisoptions property takes precedence. timeZone - The time zone to use. Can be any IANA time zone name, including named identifiers such as "UTC" ,"America/New_York" , and"Etc/GMT+8" , and offset identifiers such as"+01:00" ,"-2359" , and"+23" . The default is the runtime's time zone, the same time zone used byDate.prototype.toString() . Date-time component options weekday - The representation of the weekday. Possible values are: era - The representation of the era. Possible values are: year - The representation of the year. Possible values are "numeric" and"2-digit" . month - The representation of the month. Possible values are: day - The representation of the day. Possible values are "numeric" and"2-digit" . dayPeriod - The formatting style used for day periods like "in the morning", "am", "noon", "n" etc. Possible values are "narrow" ,"short" , and"long" .Note: This option only has an effect if a 12-hour clock ( hourCycle: "h12" orhourCycle: "h11" ) is used. Many locales use the same string irrespective of the width specified. hour - The representation of the hour. Possible values are "numeric" and"2-digit" . minute - The representation of the minute. Possible values are "numeric" and"2-digit" . second - The representation of the second. Possible values are "numeric" and"2-digit" . fractionalSecondDigits - The number of digits used to represent fractions of a second (any additional digits are truncated). Possible values are from 1 to3 . timeZoneName - The localized representation of the time zone name. Possible values are: "long" - Long localized form (e.g., Pacific Standard Time ,Nordamerikanische Westküsten-Normalzeit ) "short" - Short localized form (e.g.: PST ,GMT-8 ) "shortOffset" - Short localized GMT format (e.g., GMT-8 ) "longOffset" - Long localized GMT format (e.g., GMT-08:00 ) "shortGeneric" - Short generic non-location format (e.g.: PT ,Los Angeles Zeit ). "longGeneric" - Long generic non-location format (e.g.: Pacific Time ,Nordamerikanische Westküstenzeit ) Note: Timezone display may fall back to another format if a required string is unavailable. For example, the non-location formats should display the timezone without a specific country/city location like "Pacific Time", but may fall back to a timezone like "Los Angeles Time". Date-time component default values If any of the date-time component options are specified, then dateStyle and timeStyle must be undefined . If all date-time component options and dateStyle /timeStyle are undefined , some default options for date-time components are set, which depend on the object that the formatting method was called with: - When formatting Temporal.PlainDate andDate ,year ,month , andday default to"numeric" . - When formatting Temporal.PlainTime ,hour ,minute , andsecond default to"numeric" . - When formatting Temporal.PlainYearMonth ,year andmonth default to"numeric" . - When formatting Temporal.PlainMonthDay ,month andday default to"numeric" . - When formatting Temporal.PlainDateTime andTemporal.Instant ,year ,month ,day ,hour ,minute , andsecond default to"numeric" . Format matching Implementations are required to support displaying at least the following subsets of date-time components: weekday ,year ,month ,day ,hour ,minute ,second weekday ,year ,month ,day year ,month ,day year ,month month ,day hour ,minute ,second hour ,minute The date-time component styles requested might not directly correspond to a valid format supported by the locale, so the format matcher allows you to specify how to match the requested styles to the closest supported format. formatMatcher - The format matching algorithm to use. Possible values are "basic" and"best fit" ; the default is"best fit" . The algorithm for"best fit" is implementation-defined, and"basic" is defined by the spec. This option is only used when bothdateStyle andtimeStyle areundefined (so that each date-time component's format is individually customizable). Style shortcuts dateStyle - The date formatting style to use. Possible values are "full" ,"long" ,"medium" , and"short" . It expands to styles forweekday ,day ,month ,year , andera , with the exact combination of values depending on the locale. When formatting objects such asTemporal.PlainDate ,Temporal.PlainYearMonth , andTemporal.PlainMonthDay ,dateStyle will resolve to only those fields relevant to the object. timeStyle - The time formatting style to use. Possible values are "full" ,"long" ,"medium" , and"short" . It expands to styles forhour ,minute ,second , andtimeZoneName , with the exact combination of values depending on the locale. Note: dateStyle and timeStyle can be used with each other, but not with other date-time component options (e.g., weekday , hour , month , etc.). You can format different object types depending on which of the style shortcut options you include: - If the dateStyle is specified, then you can formatTemporal.PlainDate ,Temporal.PlainYearMonth , andTemporal.PlainMonthDay objects. - If the timeStyle is specified, then you can formatTemporal.PlainTime objects. - If either dateStyle ortimeStyle is specified, then you can formatTemporal.PlainDateTime andDate objects. Return value A new Intl.DateTimeFormat 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.DateTimeFormat() can be called with or without new , and a new Intl.DateTimeFormat instance is returned in both cases. However, if the this value is an object that is instanceof Intl.DateTimeFormat (doesn't necessarily mean it's created via new Intl.DateTimeFormat ; just that it has Intl.DateTimeFormat.prototype in its prototype chain), then the value of this is returned instead, with the newly created Intl.DateTimeFormat object hidden in a [Symbol(IntlLegacyConstructedSymbol)] property (a unique symbol that's reused between instances). const formatter = Intl.DateTimeFormat.call( { __proto__: Intl.DateTimeFormat.prototype }, "en-US", { dateStyle: "full" }, ); console.log(Object.getOwnPropertyDescriptors(formatter)); // { // [Symbol(IntlLegacyConstructedSymbol)]: { // value: DateTimeFormat [Intl.DateTimeFormat] {}, // writable: false, // enumerable: false, // configurable: false // } // } Note that there's only one actual Intl.DateTimeFormat 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: "TypeError: formatRange method called on incompatible Object", because those methods don't consult the hidden instance's options. This behavior, called ChainDateTimeFormat , does not happen when Intl.DateTimeFormat() is called without new but with this set to anything else that's not an instanceof Intl.DateTimeFormat . If you call it directly as Intl.DateTimeFormat() , the this value is Intl , and a new Intl.DateTimeFormat instance is created normally. Exceptions RangeError - Thrown if locales oroptions contain invalid values. 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 timeStyle and dateStyle dateStyle and timeStyle provide a shortcut for setting multiple date-time component options at once. For example, for en-US , dateStyle: "short" is equivalent to setting year: "2-digit", month: "numeric", day: "numeric" , and timeStyle: "short" is equivalent to setting hour: "numeric", minute: "numeric" . const shortTime = new Intl.DateTimeFormat("en-US", { timeStyle: "short", }); console.log(shortTime.format(Date.now())); // "1:31 PM" const shortDate = new Intl.DateTimeFormat("en-US", { dateStyle: "short", }); console.log(shortDate.format(Date.now())); // "7/7/20" const mediumTime = new Intl.DateTimeFormat("en-US", { timeStyle: "medium", dateStyle: "short", }); console.log(mediumTime.format(Date.now())); // "7/7/20, 1:31:55 PM" However, the exact (locale dependent) component styles they resolve to are not included in the resolved options. This ensures the result of resolvedOptions() can be passed directly to the Intl.DateTimeFormat() constructor (because an options object with both dateStyle or timeStyle and individual date or time component styles is not valid). console.log(shortDate.resolvedOptions().year); // undefined Using dayPeriod Use the dayPeriod option to output a string for the times of day ("in the morning", "at night", "noon", etc.). Note, that this only works when formatting for a 12 hour clock (hourCycle: 'h12' or hourCycle: 'h11' ) and that for many locales the strings are the same irrespective of the value passed for the dayPeriod . const date = Date.UTC(2012, 11, 17, 4, 0, 42); console.log( new Intl.DateTimeFormat("en-GB", { hour: "numeric", hourCycle: "h12", dayPeriod: "short", timeZone: "UTC", }).format(date), ); // 4 at night" (same formatting in en-GB for all dayPeriod values) console.log( new Intl.DateTimeFormat("fr", { hour: "numeric", hourCycle: "h12", dayPeriod: "narrow", timeZone: "UTC", }).format(date), ); // "4 mat." (same output in French for both narrow/short dayPeriod) console.log( new Intl.DateTimeFormat("fr", { hour: "numeric", hourCycle: "h12", dayPeriod: "long", timeZone: "UTC", }).format(date), ); // "4 du matin" Using timeZoneName Use the timeZoneName option to output a string for the timezone ("GMT", "Pacific Time", etc.). const date = Date.UTC(2021, 11, 17, 3, 0, 42); const timezoneNames = [ "short", "long", "shortOffset", "longOffset", "shortGeneric", "longGeneric", ]; for (const zoneName of timezoneNames) { // Do something with currentValue const formatter = new Intl.DateTimeFormat("en-US", { timeZone: "America/Los_Angeles", timeZoneName: zoneName, }); console.log(`${zoneName}: ${formatter.format(date)}`); } // Logs: // short: 12/16/2021, PST // long: 12/16/2021, Pacific Standard Time // shortOffset: 12/16/2021, GMT-8 // longOffset: 12/16/2021, GMT-08:00 // shortGeneric: 12/16/2021, PT // longGeneric: 12/16/2021, Pacific Time Specifications | Specification | |---| | ECMAScript® 2026 Internationalization API Specification # sec-intl-datetimeformat-constructor |
[ "const date = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));\n// Results below assume UTC timezone - your results may vary\n\n// Specify default date formatting for language (locale)\nconsole.log(new Intl.DateTimeFormat(\"en-US\").format(date));\n// Expected output: \"12/20/2020\"\n\n// Specify default date formatting for language with a fallback language (in this case Indonesian)\nconsole.log(new Intl.DateTimeFormat([\"ban\", \"id\"]).format(date));\n// Expected output: \"20/12/2020\"\n\n// Specify date and time format using \"style\" options (i.e. full, long, medium, short)\nconsole.log(\n new Intl.DateTimeFormat(\"en-GB\", {\n dateStyle: \"full\",\n timeStyle: \"long\",\n timeZone: \"Australia/Sydney\",\n }).format(date),\n);\n// Expected output: \"Sunday, 20 December 2020 at 14:23:16 GMT+11\"\n", "new Intl.DateTimeFormat()\nnew Intl.DateTimeFormat(locales)\nnew Intl.DateTimeFormat(locales, options)\n\nIntl.DateTimeFormat()\nIntl.DateTimeFormat(locales)\nIntl.DateTimeFormat(locales, options)\n", "const formatter = Intl.DateTimeFormat.call(\n { __proto__: Intl.DateTimeFormat.prototype },\n \"en-US\",\n { dateStyle: \"full\" },\n);\nconsole.log(Object.getOwnPropertyDescriptors(formatter));\n// {\n// [Symbol(IntlLegacyConstructedSymbol)]: {\n// value: DateTimeFormat [Intl.DateTimeFormat] {},\n// writable: false,\n// enumerable: false,\n// configurable: false\n// }\n// }\n", "const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n\n// toLocaleString without arguments depends on the implementation,\n// the default locale, and the default time zone\nconsole.log(new Intl.DateTimeFormat().format(date));\n// \"12/19/2012\" if run with en-US locale (language) and time zone America/Los_Angeles (UTC-0800)\n", "const shortTime = new Intl.DateTimeFormat(\"en-US\", {\n timeStyle: \"short\",\n});\nconsole.log(shortTime.format(Date.now())); // \"1:31 PM\"\n\nconst shortDate = new Intl.DateTimeFormat(\"en-US\", {\n dateStyle: \"short\",\n});\nconsole.log(shortDate.format(Date.now())); // \"7/7/20\"\n\nconst mediumTime = new Intl.DateTimeFormat(\"en-US\", {\n timeStyle: \"medium\",\n dateStyle: \"short\",\n});\nconsole.log(mediumTime.format(Date.now())); // \"7/7/20, 1:31:55 PM\"\n", "console.log(shortDate.resolvedOptions().year); // undefined\n", "const date = Date.UTC(2012, 11, 17, 4, 0, 42);\n\nconsole.log(\n new Intl.DateTimeFormat(\"en-GB\", {\n hour: \"numeric\",\n hourCycle: \"h12\",\n dayPeriod: \"short\",\n timeZone: \"UTC\",\n }).format(date),\n);\n// 4 at night\" (same formatting in en-GB for all dayPeriod values)\n\nconsole.log(\n new Intl.DateTimeFormat(\"fr\", {\n hour: \"numeric\",\n hourCycle: \"h12\",\n dayPeriod: \"narrow\",\n timeZone: \"UTC\",\n }).format(date),\n);\n// \"4 mat.\" (same output in French for both narrow/short dayPeriod)\n\nconsole.log(\n new Intl.DateTimeFormat(\"fr\", {\n hour: \"numeric\",\n hourCycle: \"h12\",\n dayPeriod: \"long\",\n timeZone: \"UTC\",\n }).format(date),\n);\n// \"4 du matin\"\n", "const date = Date.UTC(2021, 11, 17, 3, 0, 42);\nconst timezoneNames = [\n \"short\",\n \"long\",\n \"shortOffset\",\n \"longOffset\",\n \"shortGeneric\",\n \"longGeneric\",\n];\n\nfor (const zoneName of timezoneNames) {\n // Do something with currentValue\n const formatter = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: \"America/Los_Angeles\",\n timeZoneName: zoneName,\n });\n console.log(`${zoneName}: ${formatter.format(date)}`);\n}\n\n// Logs:\n// short: 12/16/2021, PST\n// long: 12/16/2021, Pacific Standard Time\n// shortOffset: 12/16/2021, GMT-8\n// longOffset: 12/16/2021, GMT-08:00\n// shortGeneric: 12/16/2021, PT\n// longGeneric: 12/16/2021, Pacific Time\n" ]
JavaScript
mdn
4,448
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Now/plainDateISO
Temporal.Now.plainDateISO()
Temporal.Now.plainDateISO() Limited availability This feature is not Baseline because it does not work in some of the most widely-used browsers. The Temporal.Now.plainDateISO() static method returns the current date as a Temporal.PlainDate object, in the ISO 8601 calendar and the specified time zone. Syntax Temporal.Now.plainDateISO() Temporal.Now.plainDateISO(timeZone) Parameters timeZone Optional- Either a string or a Temporal.ZonedDateTime instance representing the time zone to interpret the system time in. If aTemporal.ZonedDateTime instance, its time zone is used. If a string, it can be a named time zone identifier, an offset time zone identifier, or a date-time string containing a time zone identifier or an offset (see time zones and offsets for more information). Return value The current date in the specified time zone, as a Temporal.PlainDate object using the ISO 8601 calendar. Exceptions RangeError - Thrown if the time zone is invalid. Examples Using Temporal.Now.plainDateISO() // The current date in the system's time zone const date = Temporal.Now.plainDateISO(); console.log(date); // e.g.: 2021-10-01 // The current date in the "America/New_York" time zone const dateInNewYork = Temporal.Now.plainDateISO("America/New_York"); console.log(dateInNewYork); // e.g.: 2021-09-30 Specifications | Specification | |---| | Temporal # sec-temporal.now.plaindateiso |
[ "Temporal.Now.plainDateISO()\nTemporal.Now.plainDateISO(timeZone)\n", "// The current date in the system's time zone\nconst date = Temporal.Now.plainDateISO();\nconsole.log(date); // e.g.: 2021-10-01\n\n// The current date in the \"America/New_York\" time zone\nconst dateInNewYork = Temporal.Now.plainDateISO(\"America/New_York\");\nconsole.log(dateInNewYork); // e.g.: 2021-09-30\n" ]
JavaScript
mdn
437
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality
Strict inequality (!==)
Strict inequality (!==) 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 strict inequality (!== ) operator checks whether its two operands are not equal, returning a Boolean result. Unlike the inequality operator, the strict inequality operator always considers operands of different types to be different. Try it console.log(1 !== 1); // Expected output: false console.log("hello" !== "hello"); // Expected output: false console.log("1" !== 1); // Expected output: true console.log(0 !== false); // Expected output: true Syntax x !== y Description The strict inequality operator checks whether its operands are not equal. It is the negation of the strict equality operator so the following two lines will always give the same result: x !== y; !(x === y); For details of the comparison algorithm, see the page for the strict equality operator. Like the strict equality operator, the strict inequality operator will always consider operands of different types to be different: 3 !== "3"; // true Examples Comparing operands of the same type "hello" !== "hello"; // false "hello" !== "hola"; // true 3 !== 3; // false 3 !== 4; // true true !== true; // false true !== false; // true null !== null; // false Comparing operands of different types "3" !== 3; // true true !== 1; // true null !== undefined; // true Comparing objects const object1 = { key: "value", }; const object2 = { key: "value", }; console.log(object1 !== object2); // true console.log(object1 !== object1); // false Specifications | Specification | |---| | ECMAScript® 2026 Language Specification # sec-equality-operators |
[ "console.log(1 !== 1);\n// Expected output: false\n\nconsole.log(\"hello\" !== \"hello\");\n// Expected output: false\n\nconsole.log(\"1\" !== 1);\n// Expected output: true\n\nconsole.log(0 !== false);\n// Expected output: true\n", "x !== y\n", "x !== y;\n\n!(x === y);\n", "3 !== \"3\"; // true\n", "\"hello\" !== \"hello\"; // false\n\"hello\" !== \"hola\"; // true\n\n3 !== 3; // false\n3 !== 4; // true\n\ntrue !== true; // false\ntrue !== false; // true\n\nnull !== null; // false\n", "\"3\" !== 3; // true\ntrue !== 1; // true\nnull !== undefined; // true\n", "const object1 = {\n key: \"value\",\n};\n\nconst object2 = {\n key: \"value\",\n};\n\nconsole.log(object1 !== object2); // true\nconsole.log(object1 !== object1); // false\n" ]
JavaScript
mdn
591
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/description/contributors.txt
null
# Contributors by commit history https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/symbol/description/index.md # Original Wiki contributors wbamberg fscholz ddbeck sideshowbarker ExE-Boss turtlemaster19 LJHarb
[]
JavaScript
mdn
64
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/asUintN/contributors.txt
null
# Contributors by commit history https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/bigint/asuintn/index.md # Original Wiki contributors fscholz mfuji09 wbamberg AnyhowStep sideshowbarker ExE-Boss
[]
JavaScript
mdn
60
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar/contributors.txt
null
# Contributors by commit history https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/lexical_grammar/index.md # Original Wiki contributors iwhoisrishabh hinell wbamberg fscholz lucaswerkmeister neverRare LeonFrempong mfuji09 Aljullu rwaldron jinbeomhong alattalatta Nux chrisdavidmills irenesmith zhaoyingdu myakura Waldo GSRyu Erutuon mistoken nmve kdex lewisje fasttime Pointy stevemao michaelficarra merih Hywan akinjide KiraAndMaxim realityking jpmedley LoTD Minat Penny jensen morello jscape RogerPoon shvaikalesh zzmp williampower
[]
JavaScript
mdn
141
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/format/contributors.txt
null
# Contributors by commit history https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/durationformat/format/index.md
[]
JavaScript
mdn
41
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Key_not_weakly_held/contributors.txt
null
# Contributors by commit history https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/errors/key_not_weakly_held/index.md
[]
JavaScript
mdn
37
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Malformed_URI
URIError: malformed URI sequence
URIError: malformed URI sequence The JavaScript exception "malformed URI sequence" occurs when URI encoding or decoding wasn't successful. Message URIError: URI malformed (V8-based) URIError: malformed URI sequence (Firefox) URIError: String contained an illegal UTF-16 sequence. (Safari) Error type URIError What went wrong? URI encoding or decoding wasn't successful. An argument given to either the decodeURI , encodeURI , encodeURIComponent , or decodeURIComponent function was not valid, so that the function was unable encode or decode properly. Examples Encoding Encoding replaces each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character. An URIError will be thrown if there is an attempt to encode a surrogate which is not part of a high-low pair, for example: encodeURI("\uD800"); // "URIError: malformed URI sequence" encodeURI("\uDFFF"); // "URIError: malformed URI sequence" A high-low pair is OK. For example: encodeURI("\uD800\uDFFF"); // "%F0%90%8F%BF" Decoding Decoding replaces each escape sequence in the encoded URI component with the character that it represents. If there isn't such a character, an error will be thrown: decodeURIComponent("%E0%A4%A"); // "URIError: malformed URI sequence" With proper input, this should usually look like something like this: decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"); // "JavaScript_шеллы"
[ "encodeURI(\"\\uD800\");\n// \"URIError: malformed URI sequence\"\n\nencodeURI(\"\\uDFFF\");\n// \"URIError: malformed URI sequence\"\n", "encodeURI(\"\\uD800\\uDFFF\");\n// \"%F0%90%8F%BF\"\n", "decodeURIComponent(\"%E0%A4%A\");\n// \"URIError: malformed URI sequence\"\n", "decodeURIComponent(\"JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B\");\n// \"JavaScript_шеллы\"\n" ]
JavaScript
mdn
440
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length
Function: length
Function: length 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 length data property of a Function instance indicates the number of parameters expected by the function. Try it function func1() {} function func2(a, b) {} console.log(func1.length); // Expected output: 0 console.log(func2.length); // Expected output: 2 Value A number. Property attributes of Function: length | | |---|---| | Writable | no | | Enumerable | no | | Configurable | yes | Description A Function object's length property indicates how many arguments the function expects, i.e., the number of formal parameters: - Only parameters before the first one with a default value are counted. - A destructuring pattern counts as a single parameter. - The rest parameter is excluded. By contrast, arguments.length is local to a function and provides the number of arguments actually passed to the function. The Function constructor is itself a Function object. Its length data property has a value of 1 . Due to historical reasons, Function.prototype is a callable itself. The length property of Function.prototype has a value of 0 . Examples Using function length console.log(Function.length); // 1 console.log((() => {}).length); // 0 console.log(((a) => {}).length); // 1 console.log(((a, b) => {}).length); // 2 etc. console.log(((...args) => {}).length); // 0, rest parameter is not counted console.log(((a, b = 1, c) => {}).length); // 1, only parameters before the first one with // a default value are counted console.log((({ a, b }, [c, d]) => {}).length); // 2, destructuring patterns each count as // a single parameter Specifications | Specification | |---| | ECMAScript® 2026 Language Specification # sec-function-instances-length |
[ "function func1() {}\n\nfunction func2(a, b) {}\n\nconsole.log(func1.length);\n// Expected output: 0\n\nconsole.log(func2.length);\n// Expected output: 2\n", "console.log(Function.length); // 1\n\nconsole.log((() => {}).length); // 0\nconsole.log(((a) => {}).length); // 1\nconsole.log(((a, b) => {}).length); // 2 etc.\n\nconsole.log(((...args) => {}).length);\n// 0, rest parameter is not counted\n\nconsole.log(((a, b = 1, c) => {}).length);\n// 1, only parameters before the first one with\n// a default value are counted\n\nconsole.log((({ a, b }, [c, d]) => {}).length);\n// 2, destructuring patterns each count as\n// a single parameter\n" ]
JavaScript
mdn
611
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_delete
TypeError: property "x" is non-configurable and can't be deleted
TypeError: property "x" is non-configurable and can't be deleted The JavaScript exception "property is non-configurable and can't be deleted" occurs when it was attempted to delete a property, but that property is non-configurable. Message TypeError: Cannot delete property 'x' of #<Object> (V8-based) TypeError: property "x" is non-configurable and can't be deleted (Firefox) TypeError: Unable to delete property. (Safari) Error type TypeError in strict mode only. What went wrong? It was attempted to delete a property, but that property is non-configurable. The configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable ) can be changed. This error happens only in strict mode code. In non-strict code, the operation returns false . Examples Attempting to delete non-configurable properties Non-configurable properties are not super common, but they can be created using Object.defineProperty() or Object.freeze() . "use strict"; const obj = Object.freeze({ name: "Elsa", score: 157 }); delete obj.score; // TypeError "use strict"; const obj = {}; Object.defineProperty(obj, "foo", { value: 2, configurable: false }); delete obj.foo; // TypeError "use strict"; const frozenArray = Object.freeze([0, 1, 2]); frozenArray.pop(); // TypeError There are also a few non-configurable properties built into JavaScript. Maybe you tried to delete a mathematical constant. "use strict"; delete Math.PI; // TypeError
[ "\"use strict\";\nconst obj = Object.freeze({ name: \"Elsa\", score: 157 });\ndelete obj.score; // TypeError\n", "\"use strict\";\nconst obj = {};\nObject.defineProperty(obj, \"foo\", { value: 2, configurable: false });\ndelete obj.foo; // TypeError\n", "\"use strict\";\nconst frozenArray = Object.freeze([0, 1, 2]);\nfrozenArray.pop(); // TypeError\n", "\"use strict\";\ndelete Math.PI; // TypeError\n" ]
JavaScript
mdn
461
End of preview.

No dataset card yet

Downloads last month
11