diff --git "a/data/javascript/train.jsonl" "b/data/javascript/train.jsonl" new file mode 100644--- /dev/null +++ "b/data/javascript/train.jsonl" @@ -0,0 +1,173 @@ +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/json/parse/index.md\n\n# Original Wiki contributors\nmfuji09\nSebastianSimon\nwbamberg\nhikigaya58\nfscholz\nnakhodkiin\nanonyco\nSphinxKnight\nRichienb\nalattalatta\nschalkneethling\nwhirr.click\nbartolocarrasco\njameshkramer\nkeirog\ndavid_ross\nFredGandt\nkdex\noksana-khristenko\nccoenen\nNodeGuy\nSheppy\nduraik3\neduardoboucas\nyortus\njordanbtucker\nkmaglione\nElFelli\nMingun\nbroadl21\ngeorgebatalinski\nziyunfei\nDCK\nmadarche\nethertank\nevilpie\nmarcello.nuccio\nWaldo\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 142} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Symbol.hasInstance", "title": "Function.prototype[Symbol.hasInstance]()", "content": "Function.prototype[Symbol.hasInstance]()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since April 2017.\nThe [Symbol.hasInstance]()\nmethod of Function\ninstances 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\noperator.\nSyntax\nfunc[Symbol.hasInstance](value)\nParameters\nvalue\n-\nThe object to test. Primitive values always return\nfalse\n.\nReturn value\ntrue\nif func.prototype\nis in the prototype chain of value\n; otherwise, false\n. Always returns false\nif value\nis not an object or this\nis not a function. If this\nis a bound function, returns the result of an instanceof\ntest on value\nand the underlying target function.\nExceptions\nTypeError\n-\nThrown if\nthis\nis not a bound function andthis.prototype\nis not an object.\nDescription\nThe instanceof\noperator calls the [Symbol.hasInstance]()\nmethod of the right-hand side whenever such a method exists. Because all functions inherit from Function.prototype\nby default, they would all have the [Symbol.hasInstance]()\nmethod, so most of the time, the Function.prototype[Symbol.hasInstance]()\nmethod specifies the behavior of instanceof\nwhen the right-hand side is a function. This method implements the default behavior of the instanceof\noperator (the same algorithm when constructor\nhas no [Symbol.hasInstance]()\nmethod).\nUnlike most methods, the Function.prototype[Symbol.hasInstance]()\nproperty 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.\nExamples\nReverting to default instanceof behavior\nYou would rarely need to call this method directly. Instead, this method is called by the instanceof\noperator. You should expect the two results to usually be equivalent.\nclass Foo {}\nconst foo = new Foo();\nconsole.log(foo instanceof Foo === Foo[Symbol.hasInstance](foo)); // true\nYou may want to use this method if you want to invoke the default instanceof\nbehavior, but you don't know if a constructor has an overridden [Symbol.hasInstance]()\nmethod.\nclass Foo {\nstatic [Symbol.hasInstance](value) {\n// A custom implementation\nreturn false;\n}\n}\nconst foo = new Foo();\nconsole.log(foo instanceof Foo); // false\nconsole.log(Function.prototype[Symbol.hasInstance].call(Foo, foo)); // true\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-function.prototype-%symbol.hasinstance% |", "code_snippets": ["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"], "language": "JavaScript", "source": "mdn", "token_count": 752} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/formatToParts", "title": "Intl.ListFormat.prototype.formatToParts()", "content": "Intl.ListFormat.prototype.formatToParts()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since April 2021.\nThe formatToParts()\nmethod of Intl.ListFormat\ninstances returns an array of objects representing each part of the formatted string that would be returned by format()\n. It is useful for building custom strings from the locale-specific tokens.\nTry it\nconst vehicles = [\"Motorcycle\", \"Bus\", \"Car\"];\nconst formatterEn = new Intl.ListFormat(\"en\", {\nstyle: \"long\",\ntype: \"conjunction\",\n});\nconst formatterFr = new Intl.ListFormat(\"fr\", {\nstyle: \"long\",\ntype: \"conjunction\",\n});\nconst partValuesEn = formatterEn.formatToParts(vehicles).map((p) => p.value);\nconst partValuesFr = formatterFr.formatToParts(vehicles).map((p) => p.value);\nconsole.log(partValuesEn);\n// Expected output: \"[\"Motorcycle\", \", \", \"Bus\", \", and \", \"Car\"]\"\nconsole.log(partValuesFr);\n// Expected output: \"[\"Motorcycle\", \", \", \"Bus\", \" et \", \"Car\"]\"\nSyntax\nformatToParts(list)\nParameters\nlist\n-\nAn 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.\nReturn value\nAn Array\nof objects containing the formatted list in parts. Each object has two properties, type\nand value\n, each containing a string. The string concatenation of value\n, in the order provided, will result in the same string as format()\n. The type\nmay be one of the following:\nExamples\nUsing formatToParts()\nconst fruits = [\"Apple\", \"Orange\", \"Pineapple\"];\nconst myListFormat = new Intl.ListFormat(\"en-GB\", {\nstyle: \"long\",\ntype: \"conjunction\",\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// ]\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # sec-Intl.ListFormat.prototype.formatToParts |", "code_snippets": ["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"], "language": "JavaScript", "source": "mdn", "token_count": 795} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString", "title": "Date.prototype.toISOString()", "content": "Date.prototype.toISOString()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe toISOString()\nmethod of Date\ninstances 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\nor \u00b1YYYYYY-MM-DDTHH:mm:ss.sssZ\n, respectively). The timezone is always UTC, as denoted by the suffix Z\n.\nTry it\nconst 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\nconsole.log(event.toISOString());\n// Expected output: \"2011-10-05T14:48:00.000Z\"\nSyntax\ntoISOString()\nParameters\nNone.\nReturn value\nA 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()\n.\nExceptions\nRangeError\n-\nThrown if the date is invalid or if it corresponds to a year that cannot be represented in the date string format.\nExamples\nUsing toISOString()\nconst d = new Date(0);\nconsole.log(d.toISOString()); // \"1970-01-01T00:00:00.000Z\"\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-date.prototype.toisostring |", "code_snippets": ["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"], "language": "JavaScript", "source": "mdn", "token_count": 433} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction_assignment", "title": "Subtraction assignment (-=)", "content": "Subtraction assignment (-=)\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe subtraction assignment (-=\n) operator performs subtraction on the two operands and assigns the result to the left operand.\nTry it\nlet a = 2;\nconsole.log((a -= 3));\n// Expected output: -1\nconsole.log((a -= \"Hello\"));\n// Expected output: NaN\nSyntax\njs\nx -= y\nDescription\nx -= y\nis equivalent to x = x - y\n, except that the expression x\nis only evaluated once.\nExamples\nSubtraction assignment using numbers\njs\nlet bar = 5;\nbar -= 2; // 3\nOther non-BigInt values are coerced to numbers:\njs\nbar -= \"foo\"; // NaN\nSubtraction assignment using BigInts\njs\nlet foo = 3n;\nfoo -= 2n; // 1n\nfoo -= 1; // TypeError: Cannot mix BigInt and other types, use explicit conversions\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-assignment-operators |", "code_snippets": ["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"], "language": "JavaScript", "source": "mdn", "token_count": 312} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat", "title": "Intl.NumberFormat() constructor", "content": "Intl.NumberFormat() constructor\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since September 2017.\nThe Intl.NumberFormat()\nconstructor creates Intl.NumberFormat\nobjects.\nTry it\nconst number = 123456.789;\nconsole.log(\nnew Intl.NumberFormat(\"de-DE\", { style: \"currency\", currency: \"EUR\" }).format(\nnumber,\n),\n);\n// Expected output: \"123.456,79 \u20ac\"\n// The Japanese yen doesn't use a minor unit\nconsole.log(\nnew Intl.NumberFormat(\"ja-JP\", { style: \"currency\", currency: \"JPY\" }).format(\nnumber,\n),\n);\n// Expected output: \"\uffe5123,457\"\n// Limit to three significant digits\nconsole.log(\nnew Intl.NumberFormat(\"en-IN\", { maximumSignificantDigits: 3 }).format(\nnumber,\n),\n);\n// Expected output: \"1,23,000\"\nSyntax\nnew Intl.NumberFormat()\nnew Intl.NumberFormat(locales)\nnew Intl.NumberFormat(locales, options)\nIntl.NumberFormat()\nIntl.NumberFormat(locales)\nIntl.NumberFormat(locales, options)\nNote:\nIntl.NumberFormat()\ncan be called with or without new\n. Both create a new Intl.NumberFormat\ninstance. However, there's a special behavior when it's called without new\nand the this\nvalue is another Intl.NumberFormat\ninstance; see Return value.\nParameters\nlocales\nOptional-\nA string with a BCP 47 language tag or an\nIntl.Locale\ninstance, or an array of such locale identifiers. The runtime's default locale is used whenundefined\nis passed or when none of the specified locale identifiers is supported. For the general form and interpretation of thelocales\nargument, see the parameter description on theIntl\nmain page.The following Unicode extension key is allowed:\nnu\n-\nSee\nnumberingSystem\n.\nThis key can also be set with\noptions\n(as listed below). When both are set, theoptions\nproperty takes precedence. options\nOptional-\nAn 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.\nLocale options\nlocaleMatcher\n-\nThe locale matching algorithm to use. Possible values are\n\"lookup\"\nand\"best fit\"\n; the default is\"best fit\"\n. For information about this option, see Locale identification and negotiation. numberingSystem\n-\nThe numbering system to use for number formatting, such as\n\"arab\"\n,\"hans\"\n,\"mathsans\"\n, and so on. For a list of supported numbering system types, seeIntl.supportedValuesOf()\n; the default is locale dependent. This option can also be set through thenu\nUnicode extension key; if both are provided, thisoptions\nproperty takes precedence.\nStyle options\nDepending on the style\nused, some of them may be ignored, and others may be required:\nstyle\n-\nThe formatting style to use.\n\"decimal\"\n(default)-\nFor plain number formatting.\n\"currency\"\n-\nFor currency formatting.\n\"percent\"\n-\nFor percent formatting.\n\"unit\"\n-\nFor unit formatting.\ncurrency\n-\nThe currency to use in currency formatting. Possible values are the ISO 4217 currency codes, such as\n\"USD\"\nfor the US dollar,\"EUR\"\nfor the euro, or\"CNY\"\nfor the Chinese RMB \u2014 seeIntl.supportedValuesOf()\n. There is no default value; if thestyle\nis\"currency\"\n, thecurrency\nproperty must be provided. It is normalized to uppercase. currencyDisplay\n-\nHow to display the currency in currency formatting.\n\"code\"\n-\nUse the ISO currency code.\n\"symbol\"\n(default)-\nUse a localized currency symbol such as \u20ac.\n\"narrowSymbol\"\n-\nUse a narrow format symbol (\"$100\" rather than \"US$100\").\n\"name\"\n-\nUse a localized currency name such as\n\"dollar\"\n.\ncurrencySign\n-\nIn many locales, accounting format means to wrap the number with parentheses instead of appending a minus sign. Possible values are\n\"standard\"\nand\"accounting\"\n; the default is\"standard\"\n. unit\n-\nThe unit to use in\nunit\nformatting. Possible values are listed inIntl.supportedValuesOf()\n. Pairs of simple units can be concatenated with \"-per-\" to make a compound unit. There is no default value; if thestyle\nis\"unit\"\n, theunit\nproperty must be provided. unitDisplay\n-\nThe unit formatting style to use in\nunit\nformatting. Possible values are:\"short\"\n(default)-\nE.g.,\n16 l\n. \"narrow\"\n-\nE.g.,\n16l\n. \"long\"\n-\nE.g.,\n16 litres\n.\nDigit options\nThe following properties are also supported by Intl.PluralRules\n.\nminimumIntegerDigits\n-\nThe 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\n1\nto21\n; the default is1\n. minimumFractionDigits\n-\nThe minimum number of fraction digits to use. Possible values are from\n0\nto100\n; the default for plain number and percent formatting is0\n; 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\n-\nThe maximum number of fraction digits to use. Possible values are from\n0\nto100\n; the default for plain number formatting is the larger ofminimumFractionDigits\nand3\n; the default for currency formatting is the larger ofminimumFractionDigits\nand 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\nand 0. See SignificantDigits/FractionDigits default values for when this default gets applied. minimumSignificantDigits\n-\nThe minimum number of significant digits to use. Possible values are from\n1\nto21\n; the default is1\n. See SignificantDigits/FractionDigits default values for when this default gets applied. maximumSignificantDigits\n-\nThe maximum number of significant digits to use. Possible values are from\n1\nto21\n; the default is21\n. See SignificantDigits/FractionDigits default values for when this default gets applied. roundingPriority\n-\nSpecify how rounding conflicts will be resolved if both \"FractionDigits\" (\nminimumFractionDigits\n/maximumFractionDigits\n) and \"SignificantDigits\" (minimumSignificantDigits\n/maximumSignificantDigits\n) are specified. Possible values are:\"auto\"\n(default)-\nThe result from the significant digits property is used.\n\"morePrecision\"\n-\nThe result from the property that results in more precision is used.\n\"lessPrecision\"\n-\nThe result from the property that results in less precision is used.\nThe value\n\"auto\"\nis normalized to\"morePrecision\"\nifnotation\nis\"compact\"\nand none of the four \"FractionDigits\"/\"SignificantDigits\" options are set.Note that for values other than\nauto\nthe result with more precision is calculated from themaximumSignificantDigits\nandmaximumFractionDigits\n(minimum fractional and significant digit settings are ignored). roundingIncrement\n-\nIndicates the increment at which rounding should take place relative to the calculated rounding magnitude. Possible values are\n1\n,2\n,5\n,10\n,20\n,25\n,50\n,100\n,200\n,250\n,500\n,1000\n,2000\n,2500\n, and5000\n; the default is1\n. It cannot be mixed with significant-digits rounding or any setting ofroundingPriority\nother thanauto\n. roundingMode\n-\nHow decimals should be rounded. Possible values are:\n\"ceil\"\n-\nRound toward +\u221e. Positive values round up. Negative values round \"more positive\".\n\"floor\"\n-\nRound toward -\u221e. Positive values round down. Negative values round \"more negative\".\n\"expand\"\n-\nRound away from 0. The magnitude of the value is always increased by rounding. Positive values round up. Negative values round \"more negative\".\n\"trunc\"\n-\nRound toward 0. This magnitude of the value is always reduced by rounding. Positive values round down. Negative values round \"less negative\".\n\"halfCeil\"\n-\nTies toward +\u221e. Values above the half-increment round like\n\"ceil\"\n(towards +\u221e), and below like\"floor\"\n(towards -\u221e). On the half-increment, values round like\"ceil\"\n. \"halfFloor\"\n-\nTies toward -\u221e. Values above the half-increment round like\n\"ceil\"\n(towards +\u221e), and below like\"floor\"\n(towards -\u221e). On the half-increment, values round like\"floor\"\n. \"halfExpand\"\n(default)-\nTies away from 0. Values above the half-increment round like\n\"expand\"\n(away from zero), and below like\"trunc\"\n(towards 0). On the half-increment, values round like\"expand\"\n. \"halfTrunc\"\n-\nTies toward 0. Values above the half-increment round like\n\"expand\"\n(away from zero), and below like\"trunc\"\n(towards 0). On the half-increment, values round like\"trunc\"\n. \"halfEven\"\n-\nTies towards the nearest even integer. Values above the half-increment round like\n\"expand\"\n(away from zero), and below like\"trunc\"\n(towards 0). On the half-increment values round towards the nearest even digit.\nThese 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.\ntrailingZeroDisplay\n-\nThe strategy for displaying trailing zeros on whole numbers. Possible values are:\n\"auto\"\n(default)-\nKeep trailing zeros according to\nminimumFractionDigits\nandminimumSignificantDigits\n. \"stripIfInteger\"\n-\nRemove the fraction digits if they are all zero. This is the same as\n\"auto\"\nif any of the fraction digits is non-zero.\nSignificantDigits/FractionDigits default values\nFor the four options above (the FractionDigits\nand SignificantDigits\noptions), 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\nand notation\nsettings. Specifically:\n- If\nroundingPriority\nis not\"auto\"\n, then all four options apply. - If\nroundingPriority\nis\"auto\"\nand at least oneSignificantDigits\noption is set, then theSignificantDigits\noptions apply and theFractionDigits\noptions are ignored. - If\nroundingPriority\nis\"auto\"\n, and either at least oneFractionDigits\noption is set ornotation\nis not\"compact\"\n, then theFractionDigits\noptions apply and theSignificantDigits\noptions are ignored. - If\nroundingPriority\nis\"auto\"\n,notation\nis\"compact\"\n, and none of the four options are set, then they are set to{ minimumFractionDigits: 0, maximumFractionDigits: 0, minimumSignificantDigits: 1, maximumSignificantDigits: 2 }\n, regardless of the defaults mentioned above, androundingPriority\nis set to\"morePrecision\"\n.\nOther options\nnotation\n-\nThe formatting that should be displayed for the number. Possible values are:\n\"standard\"\n(default)-\nPlain number formatting.\n\"scientific\"\n-\nReturn the order-of-magnitude for formatted number.\n\"engineering\"\n-\nReturn the exponent of ten when divisible by three.\n\"compact\"\n-\nString representing exponent; defaults to using the \"short\" form.\ncompactDisplay\n-\nOnly used when\nnotation\nis\"compact\"\n. Possible values are\"short\"\nand\"long\"\n; the default is\"short\"\n. useGrouping\n-\nWhether to use grouping separators, such as thousands separators or thousand/lakh/crore separators.\n\"always\"\n-\nDisplay grouping separators even if the locale prefers otherwise.\n\"auto\"\n-\nDisplay grouping separators based on the locale preference, which may also be dependent on the currency.\n\"min2\"\n-\nDisplay grouping separators when there are at least 2 digits in a group.\ntrue\n-\nSame as\n\"always\"\n. false\n-\nDisplay no grouping separators.\nThe default is\n\"min2\"\nifnotation\nis\"compact\"\n, and\"auto\"\notherwise. The string values\"true\"\nand\"false\"\nare accepted, but are always converted to the default value. signDisplay\n-\nWhen to display the sign for the number. Possible values are:\n\"auto\"\n(default)-\nSign display for negative numbers only, including negative zero.\n\"always\"\n-\nAlways display sign.\n\"exceptZero\"\n-\nSign display for positive and negative numbers, but not zero.\n\"negative\"\n-\nSign display for negative numbers only, excluding negative zero.\n\"never\"\n-\nNever display sign.\nReturn value\nA new Intl.NumberFormat\nobject.\nNote: 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.\nNormally, Intl.NumberFormat()\ncan be called with or without new\n, and a new Intl.NumberFormat\ninstance is returned in both cases. However, if the this\nvalue is an object that is instanceof\nIntl.NumberFormat\n(doesn't necessarily mean it's created via new Intl.NumberFormat\n; just that it has Intl.NumberFormat.prototype\nin its prototype chain), then the value of this\nis returned instead, with the newly created Intl.NumberFormat\nobject hidden in a [Symbol(IntlLegacyConstructedSymbol)]\nproperty (a unique symbol that's reused between instances).\nconst 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// }\nNote that there's only one actual Intl.NumberFormat\ninstance here: the one hidden in [Symbol(IntlLegacyConstructedSymbol)]\n. Calling the format()\nand resolvedOptions()\nmethods on formatter\nwould correctly use the options stored in that instance, but calling all other methods (e.g., formatRange()\n) would fail with \"TypeError: formatRange method called on incompatible Object\", because those methods don't consult the hidden instance's options.\nThis behavior, called ChainNumberFormat\n, does not happen when Intl.NumberFormat()\nis called without new\nbut with this\nset to anything else that's not an instanceof Intl.NumberFormat\n. If you call it directly as Intl.NumberFormat()\n, the this\nvalue is Intl\n, and a new Intl.NumberFormat\ninstance is created normally.\nExceptions\nRangeError\n-\nThrown in one of the following cases:\n- A property that takes enumerated values (such as\nstyle\n,units\n,currency\n, and so on) is set to an invalid value. - Both\nmaximumFractionDigits\nandminimumFractionDigits\nare 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.\n- A property that takes enumerated values (such as\nTypeError\n-\nThrown if the\noptions.style\nproperty is set to \"unit\" or \"currency\", and no value has been set for the corresponding propertyoptions.unit\noroptions.currency\n.\nExamples\nBasic usage\nIn basic use without specifying a locale, a formatted string in the default locale and with default options is returned.\nconst amount = 3500;\nconsole.log(new Intl.NumberFormat().format(amount));\n// '3,500' if in US English locale\nDecimal and percent formatting\nconst amount = 3500;\nnew Intl.NumberFormat(\"en-US\", {\nstyle: \"decimal\",\n}).format(amount); // '3,500'\nnew Intl.NumberFormat(\"en-US\", {\nstyle: \"percent\",\n}).format(amount); // '350,000%'\nUnit formatting\nIf the style\nis 'unit'\n, a unit\nproperty must be provided.\nOptionally, unitDisplay\ncontrols the unit formatting.\nconst amount = 3500;\nnew Intl.NumberFormat(\"en-US\", {\nstyle: \"unit\",\nunit: \"liter\",\n}).format(amount); // '3,500 L'\nnew Intl.NumberFormat(\"en-US\", {\nstyle: \"unit\",\nunit: \"liter\",\nunitDisplay: \"long\",\n}).format(amount); // '3,500 liters'\nCurrency formatting\nIf the style\nis 'currency'\n, a currency\nproperty\nmust be provided. Optionally, currencyDisplay\nand\ncurrencySign\ncontrol the unit formatting.\nconst amount = -3500;\nnew Intl.NumberFormat(\"en-US\", {\nstyle: \"currency\",\ncurrency: \"USD\",\n}).format(amount); // '-$3,500.00'\nnew Intl.NumberFormat(\"bn\", {\nstyle: \"currency\",\ncurrency: \"USD\",\ncurrencyDisplay: \"name\",\n}).format(amount); // '-3,500.00 US dollars'\nnew Intl.NumberFormat(\"bn\", {\nstyle: \"currency\",\ncurrency: \"USD\",\ncurrencySign: \"accounting\",\n}).format(amount); // '($3,500.00)'\nScientific, engineering or compact notations\nScientific and compact notation are represented by the notation\noption and can be formatted like this:\nnew Intl.NumberFormat(\"en-US\", {\nnotation: \"scientific\",\n}).format(987654321);\n// 9.877E8\nnew Intl.NumberFormat(\"pt-PT\", {\nnotation: \"scientific\",\n}).format(987654321);\n// 9,877E8\nnew Intl.NumberFormat(\"en-GB\", {\nnotation: \"engineering\",\n}).format(987654321);\n// 987.654E6\nnew Intl.NumberFormat(\"de\", {\nnotation: \"engineering\",\n}).format(987654321);\n// 987,654E6\nnew Intl.NumberFormat(\"zh-CN\", {\nnotation: \"compact\",\n}).format(987654321);\n// 9.9\u4ebf\nnew Intl.NumberFormat(\"fr\", {\nnotation: \"compact\",\ncompactDisplay: \"long\",\n}).format(987654321);\n// 988 millions\nnew Intl.NumberFormat(\"en-GB\", {\nnotation: \"compact\",\ncompactDisplay: \"short\",\n}).format(987654321);\n// 988M\nDisplaying signs\nDisplay a sign for positive and negative numbers, but not zero:\nnew Intl.NumberFormat(\"en-US\", {\nstyle: \"percent\",\nsignDisplay: \"exceptZero\",\n}).format(0.55);\n// '+55%'\nNote that when the currency sign is \"accounting\", parentheses might be used instead of a minus sign:\nnew Intl.NumberFormat(\"bn\", {\nstyle: \"currency\",\ncurrency: \"USD\",\ncurrencySign: \"accounting\",\nsignDisplay: \"always\",\n}).format(-3500);\n// '($3,500.00)'\nFractionDigits, SignificantDigits and IntegerDigits\nYou can specify the minimum or maximum number of fractional, integer or significant digits to display when formatting a number.\nNote:\nIf both significant and fractional digit limits are specified, then the actual formatting depends on the roundingPriority\n.\nUsing FractionDigits and IntegerDigits\nThe 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:\n// Formatting adds zeros to display minimum integers and fractions\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nminimumIntegerDigits: 3,\nminimumFractionDigits: 4,\n}).format(4.33),\n);\n// \"004.3300\"\nIf a value has more fractional digits than the specified maximum number, it will be rounded.\nThe way that it is rounded depends on the roundingMode\nproperty (more details are provided in the rounding modes section).\nBelow the value is rounded from five fractional digits (4.33145\n) to two (4.33\n):\n// Display value shortened to maximum number of digits\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nmaximumFractionDigits: 2,\n}).format(4.33145),\n);\n// \"4.33\"\nThe minimum fractional digits have no effect if the value already has more than 2 fractional digits:\n// Minimum fractions have no effect if value is higher precision.\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nminimumFractionDigits: 2,\n}).format(4.33145),\n);\n// \"4.331\"\nWarning:\nWatch out for default values as they may affect formatting even if not specified in your code.\nThe default maximum digit value is 3\nfor plain values, 2\nfor currency, and may have different values for other predefined types.\nThe formatted value above is rounded to 3 digits, even though we didn't specify the maximum digits!\nThis is because a default value of maximumFractionDigits\nis set when we specify minimumFractionDigits\n, and visa versa. The default values of maximumFractionDigits\nand minimumFractionDigits\nare 3\nand 0\n, respectively.\nYou can use resolvedOptions()\nto inspect the formatter.\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nmaximumFractionDigits: 2,\n}).resolvedOptions(),\n);\n// {\n// \u2026\n// minimumIntegerDigits: 1,\n// minimumFractionDigits: 0,\n// maximumFractionDigits: 2,\n// \u2026\n// }\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nminimumFractionDigits: 2,\n}).resolvedOptions(),\n);\n// {\n// \u2026\n// minimumIntegerDigits: 1,\n// minimumFractionDigits: 2,\n// maximumFractionDigits: 3,\n// \u2026\n// }\nUsing SignificantDigits\nThe number of significant digits is the total number of digits including both integer and fractional parts.\nThe maximumSignificantDigits\nis used to indicate the total number of digits from the original value to display.\nThe 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.\n// Display 5 significant digits\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nmaximumSignificantDigits: 5,\n}).format(54.33145),\n);\n// \"54.331\"\n// Max 2 significant digits\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nmaximumSignificantDigits: 2,\n}).format(54.33145),\n);\n// \"54\"\n// Max 1 significant digits\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nmaximumSignificantDigits: 1,\n}).format(54.33145),\n);\n// \"50\"\nThe minimumSignificantDigits\nensures that at least the specified number of digits are displayed, adding zeros to the end of the value if needed.\n// Minimum 10 significant digits\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nminimumSignificantDigits: 10,\n}).format(54.33145),\n);\n// \"54.33145000\"\nWarning:\nWatch out for default values as they may affect formatting.\nIf only one SignificantDigits\nproperty is used, then its counterpart will automatically be applied with the default value.\nThe default maximum and minimum significant digit values are 21 and 1, respectively.\nSpecifying significant and fractional digits at the same time\nThe fraction digits (minimumFractionDigits\n/maximumFractionDigits\n) and significant digits (minimumSignificantDigits\n/maximumSignificantDigits\n) are both ways of controlling how many fractional and leading digits should be formatted.\nIf both are used at the same time, it is possible for them to conflict.\nThese conflicts are resolved using the roundingPriority\nproperty.\nBy default, this has a value of \"auto\"\n, which means that if either minimumSignificantDigits\nor maximumSignificantDigits\nis specified, the fractional and integer digit properties will be ignored.\nFor example, the code below formats the value of 4.33145\nwith maximumFractionDigits: 3\n, and then maximumSignificantDigits: 2\n, and then both.\nThe value with both is the one set with maximumSignificantDigits\n.\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nmaximumFractionDigits: 3,\n}).format(4.33145),\n);\n// \"4.331\"\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nmaximumSignificantDigits: 2,\n}).format(4.33145),\n);\n// \"4.3\"\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nmaximumFractionDigits: 3,\nmaximumSignificantDigits: 2,\n}).format(4.33145),\n);\n// \"4.3\"\nUsing resolvedOptions()\nto inspect the formatter, we can see that the returned object does not include maximumFractionDigits\nwhen maximumSignificantDigits\nor minimumSignificantDigits\nare specified.\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nmaximumFractionDigits: 3,\nmaximumSignificantDigits: 2,\n}).resolvedOptions(),\n);\n// {\n// \u2026\n// minimumIntegerDigits: 1,\n// minimumSignificantDigits: 1,\n// maximumSignificantDigits: 2,\n// \u2026\n// }\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nmaximumFractionDigits: 3,\nminimumSignificantDigits: 2,\n}).resolvedOptions(),\n);\n// {\n// \u2026\n// minimumIntegerDigits: 1,\n// minimumSignificantDigits: 2,\n// maximumSignificantDigits: 21,\n// \u2026\n// }\nIn addition to \"auto\"\n, you can resolve conflicts by specifying roundingPriority\nas \"morePrecision\"\nor \"lessPrecision\"\n.\nThe formatter calculates the precision using the values of maximumSignificantDigits\nand maximumFractionDigits\n.\nThe code below shows the format being selected for the three different rounding priorities:\nconst maxFracNF = new Intl.NumberFormat(\"en\", {\nmaximumFractionDigits: 3,\n});\nconsole.log(`maximumFractionDigits:3 - ${maxFracNF.format(1.23456)}`);\n// \"maximumFractionDigits:2 - 1.235\"\nconst maxSigNS = new Intl.NumberFormat(\"en\", {\nmaximumSignificantDigits: 3,\n});\nconsole.log(`maximumSignificantDigits:3 - ${maxSigNS.format(1.23456)}`);\n// \"maximumSignificantDigits:3 - 1.23\"\nconst bothAuto = new Intl.NumberFormat(\"en\", {\nmaximumSignificantDigits: 3,\nmaximumFractionDigits: 3,\n});\nconsole.log(`auto - ${bothAuto.format(1.23456)}`);\n// \"auto - 1.23\"\nconst bothLess = new Intl.NumberFormat(\"en\", {\nroundingPriority: \"lessPrecision\",\nmaximumSignificantDigits: 3,\nmaximumFractionDigits: 3,\n});\nconsole.log(`lessPrecision - ${bothLess.format(1.23456)}`);\n// \"lessPrecision - 1.23\"\nconst bothMore = new Intl.NumberFormat(\"en\", {\nroundingPriority: \"morePrecision\",\nmaximumSignificantDigits: 3,\nmaximumFractionDigits: 3,\n});\nconsole.log(`morePrecision - ${bothMore.format(1.23456)}`);\n// \"morePrecision - 1.235\"\nNote that the algorithm can behave in an unintuitive way if a minimum value is specified without a maximum value.\nThe example below formats the value 1\nspecifying minimumFractionDigits: 2\n(formatting to 1.00\n) and minimumSignificantDigits: 2\n(formatting to 1.0\n).\nSince 1.00\nhas more digits than 1.0\n, this should be the result when prioritizing morePrecision\n, but in fact the opposite is true:\nconst bothLess = new Intl.NumberFormat(\"en\", {\nroundingPriority: \"lessPrecision\",\nminimumFractionDigits: 2,\nminimumSignificantDigits: 2,\n});\nconsole.log(`lessPrecision - ${bothLess.format(1)}`);\n// \"lessPrecision - 1.00\"\nconst bothMore = new Intl.NumberFormat(\"en\", {\nroundingPriority: \"morePrecision\",\nminimumFractionDigits: 2,\nminimumSignificantDigits: 2,\n});\nconsole.log(`morePrecision - ${bothMore.format(1)}`);\n// \"morePrecision - 1.0\"\nThe reason for this is that only the \"maximum precision\" values are used for the calculation, and the default value of maximumSignificantDigits\nis much higher than maximumFractionDigits\n.\nNote:\nThe 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).\nIt will then select the option that displays more fractional digits if morePrecision\nis set, and fewer if lessPrecision\nis set.\nThis will result in more intuitive behavior for this case.\nRounding modes\nIf 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.\nThe way in which the value is rounded depends on the roundingMode\nproperty.\nNumber formatters use halfExpand\nrounding by default, which rounds values \"away from zero\" at the half-increment (in other words, the magnitude of the value is rounded up).\nFor 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:\n// Value below half-increment: round down.\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nmaximumSignificantDigits: 2,\n}).format(2.23),\n);\n// \"2.2\"\n// Value on or above half-increment: round up.\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nmaximumSignificantDigits: 2,\n}).format(2.25),\n);\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nmaximumSignificantDigits: 2,\n}).format(2.28),\n);\n// \"2.3\"\n// \"2.3\"\nA negative number on or below the half-increment point is also rounded away from zero (becomes more negative):\n// Value below half-increment: round down.\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nmaximumSignificantDigits: 2,\n}).format(-2.23),\n);\n// \"-2.2\"\n// Value on or above half-increment: round up.\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nmaximumSignificantDigits: 2,\n}).format(-2.25),\n);\nconsole.log(\nnew Intl.NumberFormat(\"en\", {\nmaximumSignificantDigits: 2,\n}).format(-2.28),\n);\n// \"-2.3\"\n// \"-2.3\"\nThe table below show the effect of different rounding modes for positive and negative values that are on and around the half-increment.\n| rounding mode | 2.23 | 2.25 | 2.28 | -2.23 | -2.25 | -2.28 |\n|---|---|---|---|---|---|---|\nceil |\n2.3 | 2.3 | 2.3 | -2.2 | -2.2 | -2.2 |\nfloor |\n2.2 | 2.2 | 2.2 | -2.3 | -2.3 | -2.3 |\nexpand |\n2.3 | 2.3 | 2.3 | -2.3 | -2.3 | -2.3 |\ntrunc |\n2.2 | 2.2 | 2.2 | -2.2 | -2.2 | -2.2 |\nhalfCeil |\n2.2 | 2.3 | 2.3 | -2.2 | -2.2 | -2.3 |\nhalfFloor |\n2.2 | 2.2 | 2.3 | -2.2 | -2.3 | -2.3 |\nhalfExpand |\n2.2 | 2.3 | 2.3 | -2.2 | -2.3 | -2.3 |\nhalfTrunc |\n2.2 | 2.2 | 2.3 | -2.2 | -2.2 | -2.3 |\nhalfEven |\n2.2 | 2.2 | 2.3 | -2.2 | -2.2 | -2.3 |\nWhen using halfEven\n, its behavior also depends on the parity (odd or even) of the last digit of the rounded number. For example, the behavior of halfEven\nin the table above is the same as halfTrunc\n, 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 \u00b12.3 and \u00b12.4, halfEven\nwill behave like halfExpand\ninstead. This behavior avoids consistently under- or over-estimating half-increments in a large data sample.\nUsing roundingIncrement\nSometimes 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.\nThis kind of rounding can be achieved with the roundingIncrement\nproperty.\nFor example, if maximumFractionDigits\nis 2 and roundingIncrement\nis 5, then the number is rounded to the nearest 0.05:\nconst nf = new Intl.NumberFormat(\"en-US\", {\nstyle: \"currency\",\ncurrency: \"USD\",\nmaximumFractionDigits: 2,\nroundingIncrement: 5,\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\"\nThis particular pattern is referred to as \"nickel rounding\", where nickel is the colloquial name for a USA 5 cent coin.\nTo round to the nearest 10 cents (\"dime rounding\"), you could change roundingIncrement\nto 10\n.\nconst nf = new Intl.NumberFormat(\"en-US\", {\nstyle: \"currency\",\ncurrency: \"USD\",\nmaximumFractionDigits: 2,\nroundingIncrement: 10,\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\"\nYou can also use roundingMode\nto change the rounding algorithm.\nThe example below shows how halfCeil\nrounding can be used to round the value \"less positive\" below the half-rounding increment and \"more positive\" if above or on the half-increment.\nThe incremented digit is \"0.05\" so the half-increment is at .025 (below, this is shown at 11.225).\nconst nf = new Intl.NumberFormat(\"en-US\", {\nstyle: \"currency\",\ncurrency: \"USD\",\nmaximumFractionDigits: 2,\nroundingIncrement: 5,\nroundingMode: \"halfCeil\",\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\"\nIf you need to change the number of digits, remember that minimumFractionDigits\nand maximumFractionDigits\nmust both be set to the same value, or a RangeError\nis thrown.\nroundingIncrement\ncannot be mixed with significant-digits rounding or any setting of roundingPriority\nother than auto\n.\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # sec-intl-numberformat-constructor |", "code_snippets": ["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 \u20ac\"\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: \"\uffe5123,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\u4ebf\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// \u2026\n// minimumIntegerDigits: 1,\n// minimumFractionDigits: 0,\n// maximumFractionDigits: 2,\n// \u2026\n// }\n\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n minimumFractionDigits: 2,\n }).resolvedOptions(),\n);\n// {\n// \u2026\n// minimumIntegerDigits: 1,\n// minimumFractionDigits: 2,\n// maximumFractionDigits: 3,\n// \u2026\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// \u2026\n// minimumIntegerDigits: 1,\n// minimumSignificantDigits: 1,\n// maximumSignificantDigits: 2,\n// \u2026\n// }\nconsole.log(\n new Intl.NumberFormat(\"en\", {\n maximumFractionDigits: 3,\n minimumSignificantDigits: 2,\n }).resolvedOptions(),\n);\n// {\n// \u2026\n// minimumIntegerDigits: 1,\n// minimumSignificantDigits: 2,\n// maximumSignificantDigits: 21,\n// \u2026\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"], "language": "JavaScript", "source": "mdn", "token_count": 9880} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat", "title": "Intl.DurationFormat", "content": "Intl.DurationFormat\nBaseline\n2025\nNewly available\nSince March 2025, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.\nThe Intl.DurationFormat\nobject enables language-sensitive duration formatting.\nConstructor\nIntl.DurationFormat()\n-\nCreates a new\nIntl.DurationFormat\nobject.\nStatic methods\nIntl.DurationFormat.supportedLocalesOf()\n-\nReturns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.\nInstance properties\nThese properties are defined on Intl.DurationFormat.prototype\nand shared by all Intl.DurationFormat\ninstances.\nIntl.DurationFormat.prototype.constructor\n-\nThe constructor function that created the instance object. For\nIntl.DurationFormat\ninstances, the initial value is theIntl.DurationFormat\nconstructor. Intl.DurationFormat.prototype[Symbol.toStringTag]\n-\nThe initial value of the\n[Symbol.toStringTag]\nproperty is the string\"Intl.DurationFormat\"\n. This property is used inObject.prototype.toString()\n.\nInstance methods\nIntl.DurationFormat.prototype.format()\n-\nGetter function that formats a duration according to the locale and formatting options of this\nDurationFormat\nobject. Intl.DurationFormat.prototype.formatToParts()\n-\nReturns an\nArray\nof objects representing the formatted duration in parts. Intl.DurationFormat.prototype.resolvedOptions()\n-\nReturns a new object with properties reflecting the locale and formatting options computed during initialization of the object.\nExamples\nUsing Intl.DurationFormat\nThe examples below show how to use the Intl.DurationFormat\nobject to format a duration object with various locales and styles.\nconst duration = {\nhours: 1,\nminutes: 46,\nseconds: 40,\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// 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// With style set to \"narrow\" and locale \"pt\"\nnew Intl.DurationFormat(\"pt\", { style: \"narrow\" }).format(duration);\n// \"1 h 46 min 40 s\"\nSpecifications\n| Specification |\n|---|\n| Intl.DurationFormat # durationformat-objects |", "code_snippets": ["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"], "language": "JavaScript", "source": "mdn", "token_count": 697} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString", "title": "Number.prototype.toString()", "content": "Number.prototype.toString()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe toString()\nmethod of Number\nvalues returns a string representing this number value.\nTry it\nfunction hexColor(c) {\nif (c < 256) {\nreturn Math.abs(c).toString(16);\n}\nreturn 0;\n}\nconsole.log(hexColor(233));\n// Expected output: \"e9\"\nconsole.log(hexColor(\"11\"));\n// Expected output: \"b\"\nSyntax\ntoString()\ntoString(radix)\nParameters\nradix\nOptional-\nAn integer in the range\n2\nthrough36\nspecifying the base to use for representing the number value. Defaults to 10.\nReturn value\nA 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.\nExceptions\nRangeError\n-\nThrown if\nradix\nis less than 2 or greater than 36. TypeError\n-\nThrown if this method is invoked on an object that is not a\nNumber\n.\nDescription\nThe Number\nobject overrides the toString\nmethod of Object\n; it does not inherit\nObject.prototype.toString()\n. For Number\nvalues, the toString\nmethod returns a string representation of the value in the specified radix.\nFor radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) a\nthrough f\nare used.\nIf 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 -\nsign, not the two's complement of the number value.\nBoth 0\nand -0\nhave \"0\"\nas their string representation. Infinity\nreturns \"Infinity\"\nand NaN\nreturns \"NaN\"\n.\nIf the number is not a whole number, the decimal point .\nis 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.\nconsole.log((10 ** 21.5).toString()); // \"3.1622776601683794e+21\"\nconsole.log((10 ** 21.5).toString(8)); // \"526665530627250154000000\"\nThe underlying representation for floating point numbers is base-2 scientific notation (see number encoding). However, the toString()\nmethod 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()\nwill choose the one with the most 0s to the right (for any given radix).\nconsole.log((1000000000000000128).toString()); // \"1000000000000000100\"\nconsole.log(1000000000000000100 === 1000000000000000128); // true\nOn the other hand, Number.prototype.toFixed()\nand Number.prototype.toPrecision()\nallow you to specify the precision and can be more precise than toString()\n.\nThe toString()\nmethod requires its this\nvalue to be a Number\nprimitive or wrapper object. It throws a TypeError\nfor other this\nvalues without attempting to coerce them to number values.\nBecause Number\ndoesn't have a [Symbol.toPrimitive]()\nmethod, JavaScript calls the toString()\nmethod automatically when a Number\nobject is used in a context expecting a string, such as in a template literal. However, Number primitive values do not consult the toString()\nmethod to be coerced to strings \u2014 rather, they are directly converted using the same algorithm as the initial toString()\nimplementation.\nNumber.prototype.toString = () => \"Overridden\";\nconsole.log(`${1}`); // \"1\"\nconsole.log(`${new Number(1)}`); // \"Overridden\"\nExamples\nUsing toString()\nconst count = 10;\nconsole.log(count.toString()); // \"10\"\nconsole.log((17).toString()); // \"17\"\nconsole.log((17.2).toString()); // \"17.2\"\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\"\nConverting radix of number strings\nIf you have a string representing a number in a non-decimal radix, you can use parseInt()\nand toString()\nto convert it to a different radix.\nconst hex = \"CAFEBABE\";\nconst bin = parseInt(hex, 16).toString(2); // \"11001010111111101011101010111110\"\nBeware of loss of precision: if the original number string is too large (larger than Number.MAX_SAFE_INTEGER\n, for example), you should use a BigInt\ninstead. However, the BigInt\nconstructor only has support for strings representing number literals (i.e., strings starting with 0b\n, 0o\n, 0x\n). 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.\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-number.prototype.tostring |", "code_snippets": ["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"], "language": "JavaScript", "source": "mdn", "token_count": 1506} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor", "title": "Object.prototype.constructor", "content": "Object.prototype.constructor\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe constructor\ndata property of an Object\ninstance 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.\nNote:\nThis is a property of JavaScript objects. For the constructor\nmethod in classes, see its own reference page.\nValue\nA reference to the constructor function that created the instance object.\nProperty attributes of Object.prototype.constructor | |\n|---|---|\n| Writable | yes |\n| Enumerable | no |\n| Configurable | yes |\nNote:\nThis property is created by default on the prototype\nproperty of every constructor function and is inherited by all objects created by that constructor.\nDescription\nAny object (with the exception of null\nprototype objects) will have a constructor\nproperty on its [[Prototype]]\n. Objects created with literals will also have a constructor\nproperty that points to the constructor type for that object \u2014 for example, array literals create Array\nobjects, and object literals create plain objects.\nconst o1 = {};\no1.constructor === Object; // true\nconst o2 = new Object();\no2.constructor === Object; // true\nconst a1 = [];\na1.constructor === Array; // true\nconst a2 = new Array();\na2.constructor === Array; // true\nconst n = 3;\nn.constructor === Number; // true\nNote that constructor\nusually comes from the constructor's prototype\nproperty. If you have a longer prototype chain, you can usually expect every object in the chain to have a constructor\nproperty.\nconst o = new TypeError(); // Inheritance: TypeError -> Error -> Object\nconst proto = Object.getPrototypeOf;\nObject.hasOwn(o, \"constructor\"); // false\nproto(o).constructor === TypeError; // true\nproto(proto(o)).constructor === Error; // true\nproto(proto(proto(o))).constructor === Object; // true\nExamples\nDisplaying the constructor of an object\nThe following example creates a constructor (Tree\n) and an object of that type (theTree\n). The example then displays the constructor\nproperty for the object theTree\n.\nfunction Tree(name) {\nthis.name = name;\n}\nconst theTree = new Tree(\"Redwood\");\nconsole.log(`theTree.constructor is ${theTree.constructor}`);\nThis example displays the following output:\ntheTree.constructor is function Tree(name) { this.name = name; }\nAssigning the constructor property to an object\nOne can assign the constructor\nproperty of non-primitives.\nconst arr = [];\narr.constructor = String;\narr.constructor === String; // true\narr instanceof String; // false\narr instanceof Array; // true\nconst foo = new Foo();\nfoo.constructor = \"bar\";\nfoo.constructor === \"bar\"; // true\n// etc.\nThis does not overwrite the old constructor\nproperty \u2014 it was originally present on the instance's [[Prototype]]\n, not as its own property.\nconst arr = [];\nObject.hasOwn(arr, \"constructor\"); // false\nObject.hasOwn(Object.getPrototypeOf(arr), \"constructor\"); // true\narr.constructor = String;\nObject.hasOwn(arr, \"constructor\"); // true \u2014 the instance property shadows the one on its prototype\nBut even when Object.getPrototypeOf(a).constructor\nis re-assigned, it won't change other behaviors of the object. For example, the behavior of instanceof\nis controlled by Symbol.hasInstance\n, not constructor\n:\nconst arr = [];\narr.constructor = String;\narr instanceof String; // false\narr instanceof Array; // true\nThere is nothing protecting the constructor\nproperty 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\nand Symbol.toStringTag\nfor objects, or typeof\nfor primitives.\nChanging the constructor of a constructor function's prototype\nEvery constructor has a prototype\nproperty, which will become the instance's [[Prototype]]\nwhen called via the new\noperator. ConstructorFunction.prototype.constructor\nwill therefore become a property on the instance's [[Prototype]]\n, as previously demonstrated.\nHowever, if ConstructorFunction.prototype\nis re-assigned, the constructor\nproperty will be lost. For example, the following is a common way to create an inheritance pattern:\nfunction Parent() {\n// \u2026\n}\nParent.prototype.parentMethod = function () {};\nfunction Child() {\nParent.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);\nThe constructor\nof instances of Child\nwill be Parent\ndue to Child.prototype\nbeing re-assigned.\nThis is usually not a big deal \u2014 the language almost never reads the constructor\nproperty of an object. The only exception is when using [Symbol.species]\nto create new instances of a class, but such cases are rare, and you should be using the extends\nsyntax to subclass builtins anyway.\nHowever, ensuring that Child.prototype.constructor\nalways points to Child\nitself is crucial when some caller is using constructor\nto access the original class from an instance. Take the following case: the object has the create()\nmethod to create itself.\nfunction Parent() {\n// \u2026\n}\nfunction CreatedConstructor() {\nParent.call(this);\n}\nCreatedConstructor.prototype = Object.create(Parent.prototype);\nCreatedConstructor.prototype.create = function () {\nreturn new this.constructor();\n};\nnew CreatedConstructor().create().create(); // TypeError: new CreatedConstructor().create().create is undefined, since constructor === Parent\nIn the example above, an exception is thrown, since the constructor\nlinks to Parent\n. To avoid this, just assign the necessary constructor you are going to use.\nfunction Parent() {\n// \u2026\n}\nfunction CreatedConstructor() {\n// \u2026\n}\nCreatedConstructor.prototype = Object.create(Parent.prototype, {\n// Return original constructor to Child\nconstructor: {\nvalue: CreatedConstructor,\nenumerable: false, // Make it non-enumerable, so it won't appear in `for...in` loop\nwritable: true,\nconfigurable: true,\n},\n});\nCreatedConstructor.prototype.create = function () {\nreturn new this.constructor();\n};\nnew CreatedConstructor().create().create(); // it's pretty fine\nNote that when manually adding the constructor\nproperty, it's crucial to make the property non-enumerable, so constructor\nwon't be visited in for...in\nloops \u2014 as it normally isn't.\nIf the code above looks like too much boilerplate, you may also consider using Object.setPrototypeOf()\nto manipulate the prototype chain.\nfunction Parent() {\n// \u2026\n}\nfunction CreatedConstructor() {\n// \u2026\n}\nObject.setPrototypeOf(CreatedConstructor.prototype, Parent.prototype);\nCreatedConstructor.prototype.create = function () {\nreturn new this.constructor();\n};\nnew CreatedConstructor().create().create(); // still works without re-creating constructor property\nObject.setPrototypeOf()\ncomes 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\nor CreatedConstructor\nare constructed, the effect should be minimal.\nLet's consider one more involved case.\nfunction ParentWithStatic() {}\nParentWithStatic.startPosition = { x: 0, y: 0 }; // Static member property\nParentWithStatic.getStartPosition = function () {\nreturn this.startPosition;\n};\nfunction Child(x, y) {\nthis.position = { x, y };\n}\nChild.prototype = Object.create(ParentWithStatic.prototype, {\n// Return original constructor to Child\nconstructor: {\nvalue: Child,\nenumerable: false,\nwritable: true,\nconfigurable: true,\n},\n});\nChild.prototype.getOffsetByInitialPosition = function () {\nconst position = this.position;\n// Using this.constructor, in hope that getStartPosition exists as a static method\nconst startPosition = this.constructor.getStartPosition();\nreturn {\noffsetX: startPosition.x - position.x,\noffsetY: startPosition.y - position.y,\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\nFor this example to work properly, we can reassign the Parent\n's static properties to Child\n:\n// \u2026\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\nconstructor: {\nvalue: Child,\nenumerable: false,\nwritable: true,\nconfigurable: true,\n},\n});\n// \u2026\nBut even better, we can make the constructor functions themselves extend each other, as classes' extends\ndo.\nfunction ParentWithStatic() {}\nParentWithStatic.startPosition = { x: 0, y: 0 }; // Static member property\nParentWithStatic.getStartPosition = function () {\nreturn this.startPosition;\n};\nfunction Child(x, y) {\nthis.position = { x, y };\n}\n// Properly create inheritance!\nObject.setPrototypeOf(Child.prototype, ParentWithStatic.prototype);\nObject.setPrototypeOf(Child, ParentWithStatic);\nChild.prototype.getOffsetByInitialPosition = function () {\nconst position = this.position;\nconst startPosition = this.constructor.getStartPosition();\nreturn {\noffsetX: startPosition.x - position.x,\noffsetY: startPosition.y - position.y,\n};\n};\nconsole.log(new Child(1, 1).getOffsetByInitialPosition()); // { offsetX: -1, offsetY: -1 }\nAgain, using Object.setPrototypeOf()\nmay have adverse performance effects, so make sure it happens immediately after the constructor declaration and before any instances are created \u2014 to avoid objects being \"tainted\".\nNote:\nManually updating or setting the constructor can lead to different and sometimes confusing consequences. To prevent this, just define the role of constructor\nin each specific case. In most cases, constructor\nis not used and reassigning it is not necessary.\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-object.prototype.constructor |", "code_snippets": ["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 \u2014 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 // \u2026\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 // \u2026\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 // \u2026\n}\nfunction CreatedConstructor() {\n // \u2026\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 // \u2026\n}\nfunction CreatedConstructor() {\n // \u2026\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", "// \u2026\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// \u2026\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"], "language": "JavaScript", "source": "mdn", "token_count": 3724} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Symbol.toPrimitive", "title": "Date.prototype[Symbol.toPrimitive]()", "content": "Date.prototype[Symbol.toPrimitive]()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since April 2017.\nThe [Symbol.toPrimitive]()\nmethod of Date\ninstances returns a primitive value representing this date. It may either be a string or a number, depending on the hint given.\nTry it\n// Depending on timezone, your results will vary\nconst date = new Date(\"20 December 2019 14:48\");\nconsole.log(date[Symbol.toPrimitive](\"string\"));\n// Expected output: \"Fri Dec 20 2019 14:48:00 GMT+0530 (India Standard Time)\"\nconsole.log(date[Symbol.toPrimitive](\"number\"));\n// Expected output: 1576833480000\nSyntax\ndate[Symbol.toPrimitive](hint)\nParameters\nhint\n-\nA string representing the type of the primitive value to return. The following values are valid:\n\"string\"\nor\"default\"\n: The method should return a string.\"number\"\n: The method should return a number.\nReturn value\nIf hint\nis \"string\"\nor \"default\"\n, this method returns a string by coercing the this\nvalue to a string (first trying toString()\nthen trying valueOf()\n).\nIf hint\nis \"number\"\n, this method returns a number by coercing the this\nvalue to a number (first trying valueOf()\nthen trying toString()\n).\nExceptions\nTypeError\n-\nThrown if the\nhint\nargument is not one of the three valid values.\nDescription\nThe [Symbol.toPrimitive]()\nmethod is part of the type coercion protocol. JavaScript always calls the [Symbol.toPrimitive]()\nmethod in priority to convert an object to a primitive value. You rarely need to invoke the [Symbol.toPrimitive]()\nmethod yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.\nThe [Symbol.toPrimitive]()\nmethod of the Date\nobject returns a primitive value by either invoking this.valueOf()\nand returning a number, or invoking this.toString()\nand 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()\nbefore toString()\n. With the custom [Symbol.toPrimitive]()\n, new Date(0) + 1\nreturns \"Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)1\"\n(a string) instead of 1\n(a number).\nExamples\nUsing [Symbol.toPrimitive]()\nconst d = new Date(0); // 1970-01-01T00:00:00.000Z\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)\"\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-date.prototype-%symbol.toprimitive% |", "code_snippets": ["// 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"], "language": "JavaScript", "source": "mdn", "token_count": 832} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Duration/seconds", "title": "Temporal.Duration.prototype.seconds", "content": "Temporal.Duration.prototype.seconds\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe seconds\naccessor property of Temporal.Duration\ninstances returns an integer representing the number of seconds in the duration.\nUnless the duration is balanced, you cannot assume the range of this value, but you can know its sign by checking the duration's sign\nproperty. If it is balanced to a unit above seconds, the seconds\nabsolute value will be between 0 and 59, inclusive.\nThe set accessor of seconds\nis undefined\n. You cannot change this property directly. Use the with()\nmethod to create a new Temporal.Duration\nobject with the desired new value.\nExamples\nUsing seconds\njs\nconst 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 });\nconsole.log(d1.seconds); // 30\nconsole.log(d2.seconds); // -30\nconsole.log(d3.seconds); // 0\nconsole.log(d4.seconds); // 60\n// Balance d4\nconst d4Balanced = d4.round({ largestUnit: \"minutes\" });\nconsole.log(d4Balanced.seconds); // 0\nconsole.log(d4Balanced.minutes); // 1\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-get-temporal.duration.prototype.seconds |\nBrowser compatibility\nSee also\nTemporal.Duration\nTemporal.Duration.prototype.years\nTemporal.Duration.prototype.months\nTemporal.Duration.prototype.weeks\nTemporal.Duration.prototype.days\nTemporal.Duration.prototype.hours\nTemporal.Duration.prototype.minutes\nTemporal.Duration.prototype.milliseconds\nTemporal.Duration.prototype.microseconds\nTemporal.Duration.prototype.nanoseconds", "code_snippets": ["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"], "language": "JavaScript", "source": "mdn", "token_count": 555} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat", "title": "Intl.DateTimeFormat", "content": "Intl.DateTimeFormat\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since September 2017.\nThe Intl.DateTimeFormat\nobject enables language-sensitive date and time formatting.\nTry it\nconst date = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));\n// Results below assume UTC timezone - your results may vary\n// Specify default date formatting for language (locale)\nconsole.log(new Intl.DateTimeFormat(\"en-US\").format(date));\n// Expected output: \"12/20/2020\"\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// Specify date and time format using \"style\" options (i.e. full, long, medium, short)\nconsole.log(\nnew Intl.DateTimeFormat(\"en-GB\", {\ndateStyle: \"full\",\ntimeStyle: \"long\",\ntimeZone: \"Australia/Sydney\",\n}).format(date),\n);\n// Expected output: \"Sunday, 20 December 2020 at 14:23:16 GMT+11\"\nConstructor\nIntl.DateTimeFormat()\n-\nCreates a new\nIntl.DateTimeFormat\nobject.\nStatic methods\nIntl.DateTimeFormat.supportedLocalesOf()\n-\nReturns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.\nInstance properties\nThese properties are defined on Intl.DateTimeFormat.prototype\nand shared by all Intl.DateTimeFormat\ninstances.\nIntl.DateTimeFormat.prototype.constructor\n-\nThe constructor function that created the instance object. For\nIntl.DateTimeFormat\ninstances, the initial value is theIntl.DateTimeFormat\nconstructor. Intl.DateTimeFormat.prototype[Symbol.toStringTag]\n-\nThe initial value of the\n[Symbol.toStringTag]\nproperty is the string\"Intl.DateTimeFormat\"\n. This property is used inObject.prototype.toString()\n.\nInstance methods\nIntl.DateTimeFormat.prototype.format()\n-\nGetter function that formats a date according to the locale and formatting options of this\nDateTimeFormat\nobject. Intl.DateTimeFormat.prototype.formatRange()\n-\nThis method receives two Dates and formats the date range in the most concise way based on the locale and options provided when instantiating\nDateTimeFormat\n. Intl.DateTimeFormat.prototype.formatRangeToParts()\n-\nThis method receives two Dates and returns an Array of objects containing the locale-specific tokens representing each part of the formatted date range.\nIntl.DateTimeFormat.prototype.formatToParts()\n-\nReturns an\nArray\nof objects representing the date string in parts that can be used for custom locale-aware formatting. Intl.DateTimeFormat.prototype.resolvedOptions()\n-\nReturns a new object with properties reflecting the locale and formatting options computed during initialization of the object.\nExamples\nUsing DateTimeFormat\nIn basic use without specifying a locale, DateTimeFormat\nuses the default locale and default options.\nconst date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\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)\nUsing locales\nThis 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\nargument:\nconst date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n// Results below use the time zone of America/Los_Angeles (UTC-0800, Pacific Standard Time)\n// US English uses month-day-year order\nconsole.log(new Intl.DateTimeFormat(\"en-US\").format(date));\n// \"12/19/2012\"\n// British English uses day-month-year order\nconsole.log(new Intl.DateTimeFormat(\"en-GB\").format(date));\n// \"19/12/2012\"\n// Korean uses year-month-day order\nconsole.log(new Intl.DateTimeFormat(\"ko-KR\").format(date));\n// \"2012. 12. 19.\"\n// Arabic in most Arabic speaking countries uses real Arabic digits\nconsole.log(new Intl.DateTimeFormat(\"ar-EG\").format(date));\n// \"\u0661\u0669/\u0661\u0662/\u0662\u0660\u0661\u0662\"\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// 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\"\nUsing options\nThe date and time formats can be customized using the options\nargument:\nconst date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200));\n// request a weekday along with a long date\nlet options = {\nweekday: \"long\",\nyear: \"numeric\",\nmonth: \"long\",\nday: \"numeric\",\n};\nconsole.log(new Intl.DateTimeFormat(\"de-DE\", options).format(date));\n// \"Donnerstag, 20. Dezember 2012\"\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// sometimes you want to be more precise\noptions = {\nhour: \"numeric\",\nminute: \"numeric\",\nsecond: \"numeric\",\ntimeZone: \"Australia/Sydney\",\ntimeZoneName: \"short\",\n};\nconsole.log(new Intl.DateTimeFormat(\"en-AU\", options).format(date));\n// \"2:00:00 pm AEDT\"\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// sometimes even the US needs 24-hour time\noptions = {\nyear: \"numeric\",\nmonth: \"numeric\",\nday: \"numeric\",\nhour: \"numeric\",\nminute: \"numeric\",\nsecond: \"numeric\",\nhour12: false,\ntimeZone: \"America/Los_Angeles\",\n};\nconsole.log(new Intl.DateTimeFormat(\"en-US\", options).format(date));\n// \"12/19/2012, 19:00:00\"\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// 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\nThe used calendar and numbering formats can also be set independently via options\narguments:\nconst options = { calendar: \"chinese\", numberingSystem: \"arab\" };\nconst dateFormat = new Intl.DateTimeFormat(undefined, options);\nconst usedOptions = dateFormat.resolvedOptions();\nconsole.log(usedOptions.calendar);\n// \"chinese\"\nconsole.log(usedOptions.numberingSystem);\n// \"arab\"\nconsole.log(usedOptions.timeZone);\n// \"America/New_York\" (the users default timezone)\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # datetimeformat-objects |\nBrowser compatibility\nSee also\n- Polyfill of\nIntl.DateTimeFormat\nin FormatJS Intl\nDate.prototype.toLocaleString()\nDate.prototype.toLocaleDateString()\nDate.prototype.toLocaleTimeString()\nTemporal.Instant.prototype.toLocaleString()\nTemporal.PlainDate.prototype.toLocaleString()\nTemporal.PlainDateTime.prototype.toLocaleString()\nTemporal.PlainTime.prototype.toLocaleString()\nTemporal.PlainYearMonth.prototype.toLocaleString()\nTemporal.PlainMonthDay.prototype.toLocaleString()\nTemporal.ZonedDateTime.prototype.toLocaleString()", "code_snippets": ["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// \"\u0661\u0669\u200f/\u0661\u0662\u200f/\u0662\u0660\u0661\u0662\"\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"], "language": "JavaScript", "source": "mdn", "token_count": 2914} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Execution_model", "title": "JavaScript execution model", "content": "JavaScript execution model\nThis 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.\nThis 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.\nThe engine and the host\nJavaScript execution requires the cooperation of two pieces of software: the JavaScript engine and the host environment.\nThe 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.\nWhile 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.\nAgent execution model\nIn the JavaScript specification, each autonomous executor of JavaScript is called an agent, which maintains its facilities for code execution:\n- 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\nSharedArrayBuffer\nobject, 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.\n- 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.\nThese 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.\nEach 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.\nAn agent on the web can be one of the following:\n- A Similar-origin window agent, which contains various\nWindow\nobjects which can potentially reach each other, either directly or by usingdocument.domain\n. If the window is origin-keyed, then only same-origin windows can reach each other. - A Dedicated worker agent containing a single\nDedicatedWorkerGlobalScope\n. - A Shared worker agent containing a single\nSharedWorkerGlobalScope\n. - A Service worker agent containing a single\nServiceWorkerGlobalScope\n. - A Worklet agent containing a single\nWorkletGlobalScope\n.\nIn other words, each worker creates its own agent, while one or more windows may be within the same agent\u2014usually a main document and its similar-origin iframes. In Node.js, a similar concept called worker threads is available.\nThe diagram below illustrates the execution model of agents:\nRealms\nEach 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:\n- A list of intrinsic objects like\nArray\n,Array.prototype\n, etc. - Globally declared variables, the value of\nglobalThis\n, 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\nOn the web, the realm and the global object are 1-to-1 corresponded. The global object is either a Window\n, a WorkerGlobalScope\n, or a WorkletGlobalScope\n. So for example, every iframe\nexecutes in a different realm, though it may be in the same agent as the parent window.\nRealms are usually mentioned when talking about the identities of global objects. For example, we need methods such as Array.isArray()\nor Error.isError()\n, because an array constructed in another realm will have a different prototype object than the Array.prototype\nobject in the current realm, so instanceof Array\nwill wrongly return false\n.\nStack and execution contexts\nWe 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:\n- Code evaluation state\n- The module or script, the function (if applicable), and the currently executing generator that contains this code\n- The current realm\n- Bindings, including:\n- Variables defined with\nvar\n,let\n,const\n,function\n,class\n, etc. - Private identifiers like\n#foo\nwhich are only valid in the current context this\nreference\n- Variables defined with\nImagine a program consisting of a single job defined by the following code:\nfunction foo(b) {\nconst a = 10;\nreturn a + b + 11;\n}\nfunction bar(x) {\nconst y = 3;\nreturn foo(x * y);\n}\nconst baz = bar(7); // assigns 42 to baz\n- When the job starts, the first frame is created, where the variables\nfoo\n,bar\n, andbaz\nare defined. It callsbar\nwith the argument7\n. - A second frame is created for the\nbar\ncall, containing bindings for the parameterx\nand the local variabley\n. It first performs the multiplicationx * y\n, then callsfoo\nwith the result. - A third frame is created for the\nfoo\ncall, containing bindings for the parameterb\nand the local variablea\n. It first performs the additiona + b + 11\n, then returns the result. - When\nfoo\nreturns, the top frame element is popped out of the stack, and the call expressionfoo(x * y)\nresolves to the return value. It then continues execution, which is just to return this result. - When\nbar\nreturns, the top frame element is popped out of the stack, and the call expressionbar(7)\nresolves to the return value. This initializesbaz\nwith 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.\nGenerators and reentry\nWhen 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:\nfunction* gen() {\nconsole.log(1);\nyield;\nconsole.log(2);\n}\nconst g = gen();\ng.next(); // logs 1\ng.next(); // logs 2\nIn this case, calling gen()\nfirst creates an execution context which is suspended\u2014no code inside gen\ngets executed yet. The generator g\nsaves this execution context internally. The current running execution context remains to be the entrypoint. When g.next()\nis called, the execution context for gen\nis pushed onto the stack, and the code inside gen\nis executed until the yield\nexpression. Then, the generator execution context gets suspended and removed from the stack, which returns control back to the entrypoint. When g.next()\nis called again, the generator execution context is pushed back onto the stack, and the code inside gen\nresumes from where it left off.\nTail calls\nOne 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:\nfunction f() {\nreturn g();\n}\nIn this case, the call to g\nis 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()\ncall. This means that tail recursion is not subject to the stack size limits:\nfunction factorial(n, acc = 1) {\nif (n <= 1) return acc;\nreturn factorial(n - 1, n * acc);\n}\nIn reality, discarding the current frame causes debugging problems, because if g()\nthrows an error, f\nis 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.\nClosures\nAnother 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.\nlet f;\n{\nlet x = 10;\nf = () => x;\n}\nconsole.log(f()); // logs 10\nJob queue and event loop\nAn 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\u2014the 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\u2014or, in HTML terminology, an event loop\u2014once the action is completed.\nEvery 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\u2014for 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.\n\"Run-to-completion\"\nEach 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.\nFor example, consider this example:\nconst promise = Promise.resolve();\nlet i = 0;\npromise.then(() => {\ni += 1;\nconsole.log(i);\n});\npromise.then(() => {\ni += 1;\nconsole.log(i);\n});\nIn 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\nand 2\nwill 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);\nand never i += 1; i += 1; console.log(i); console.log(i);\n.\nA 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.\nNever blocking\nAnother 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()\nrequest 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()\nhandler, the callback function in setTimeout()\n, or the event handler), which defines a job to be added to the job queue once the action completes.\nOf course, the guarantee of \"never-blocking\" requires the platform API to be inherently asynchronous, but some legacy exceptions exist like alert()\nor synchronous XHR. It is considered good practice to avoid them to ensure the responsiveness of the application.\nAgent clusters and memory sharing\nMultiple 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.\nWhen 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:\n- A\nWindow\nobject and a dedicated worker that it created. - A worker (of any type) and a dedicated worker it created.\n- A\nWindow\nobject A and theWindow\nobject of a same-originiframe\nelement that A created. - A\nWindow\nobject and a same-originWindow\nobject that opened it. - A\nWindow\nobject and a worklet that it created.\nThe following pairs of global objects are not within the same agent cluster, and thus cannot share memory:\n- A\nWindow\nobject and a shared worker it created. - A worker (of any type) and a shared worker it created.\n- A\nWindow\nobject and a service worker it created. - A\nWindow\nobject A and theWindow\nobject of aniframe\nelement that A created that cannot be same origin-domain with A. - Any two\nWindow\nobjects with no opener or ancestor relationship. This holds even if the twoWindow\nobjects are same origin.\nFor the exact algorithm, check the HTML specification.\nCross-agent communication and memory model\nAs aforementioned, agents communicate via memory sharing. On the web, memory is shared via the postMessage()\nmethod. 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\nobject, which can be simultaneously accessed by multiple agents. Once two agents share access to the same memory via a SharedArrayBuffer\n, they can synchronize executions via the Atomics\nobject.\nThere 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.\nThe spec provides the following guidelines for programmers working with shared memory:\nWe 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.\nMore 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).\nConcurrency and ensuring forward progress\nWhen 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\u2014in other words, it cannot make forward progress.\nTo prevent deadlocks, there are some strong restrictions on when and which agents can become blocked.\n- Every unblocked agent with a dedicated executing thread eventually makes forward progress.\n- In a set of agents that share an executing thread, one agent eventually makes forward progress.\n- An agent does not cause another agent to become blocked except via explicit APIs that provide blocking.\n- Only certain agents can be blocked. On the web, this includes dedicated workers and shared workers, but not similar-origin windows or service workers.\nThe agent cluster ensures some level of integrity over the activeness of its agents, in the case of external pauses or terminations:\n- 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.\n- 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.)\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification |\n| ECMAScript\u00ae 2026 Language Specification |\n| HTML |\nSee also\n- Event loops in the HTML standard\n- What is the Event Loop? in the Node.js docs", "code_snippets": ["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"], "language": "JavaScript", "source": "mdn", "token_count": 5176} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/supportedValuesOf", "title": "Intl.supportedValuesOf()", "content": "Intl.supportedValuesOf()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since March 2022.\nThe Intl.supportedValuesOf()\nstatic method returns an array containing the supported calendar, collation, currency, numbering systems, or unit values supported by the implementation.\nDuplicates are omitted and the array is sorted in ascending lexicographical order (or more precisely, using Array.prototype.sort()\nwith an undefined\ncompare function).\nThe 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.\nThis 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\nobject, such as Intl.Locale.prototype.getCalendars()\n.\nTry it\nconsole.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)\ntry {\nIntl.supportedValuesOf(\"someInvalidKey\");\n} catch (err) {\nconsole.log(err.toString());\n// Expected output: RangeError: invalid key: \"someInvalidKey\"\n}\nSyntax\nIntl.supportedValuesOf(key)\nParameters\nkey\n-\nA key string indicating the category of values to be returned. This is one of:\n\"calendar\"\n: see supported calendar types\"collation\"\n: see supported collation types\"currency\"\n: see supported currency identifiers\"numberingSystem\"\n: see supported numbering system types\"timeZone\"\n: see supported time zone identifiers\"unit\"\n: see supported unit identifiers\nReturn value\nA 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.\nSupported calendar types\nBelow are all values that are commonly supported by browsers for the calendar\nkey. These values can be used for the calendar\noption or the ca\nUnicode extension key when creating objects such as Intl.DateTimeFormat\n, as well as for creating Temporal\ndate objects. This list is explicitly sanctioned by the ECMA-402 specification, so all implementations should be consistent.\n| Value | Description |\n|---|---|\nbuddhist |\nThai 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. |\nchinese |\nTraditional 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. |\ncoptic |\nCoptic calendar, proleptic. Similar solar algorithm to ethioaa and ethiopic , with one era and a different epoch year. |\ndangi |\nTraditional 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. |\nethioaa |\nEthiopic calendar, Amete Alem, proleptic. Similar solar algorithm to coptic and ethiopic , with one era and a different epoch year. |\nethiopic |\nEthiopic calendar, Amete Mihret, proleptic. Similar solar algorithm to coptic and ethioaa , with two eras and a different epoch year. |\ngregory |\nGregorian 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. |\nhebrew |\nHebrew 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. |\nindian |\nIndian national (or \u015aaka) calendar, proleptic. Solar calendar with one era. |\nislamic-civil |\nHijri 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) |\nislamic-tbla |\nHijri 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) |\nislamic-umalqura |\nHijri 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. |\niso8601 |\nISO calendar (variant of the Gregorian calendar with week rules and formatting parameters made region-independent) |\njapanese |\nJapanese 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.) |\npersian |\nPersian (or Solar Hijri) calendar, proleptic. There is one era. |\nroc |\nRepublic 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. |\nAs of October 2025, in the japanese\ncalendar, 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\ncalendar was taken into use on January 1, 6 Meiji / 1873-01-01 ISO, so these problems only affect proleptic dates.\nThe types below are specified in CLDR but do not have implementations distinct from the above calendars in browsers.\n| Value | Description | Notes |\n|---|---|---|\nethiopic-amete-alem |\nEthiopic calendar, Amete Alem, proleptic. | This is an alias for ethioaa and therefore is not returned by supportedValuesOf() . Use ethioaa instead. |\nislamic |\nHijri 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. |\nislamicc\nDeprecated\n|\nCivil (algorithmic) Arabic calendar. | This is an alias for islamic-civil and therefore is not returned by supportedValuesOf() . Use islamic-civil instead. |\nThe Temporal.PlainDate.prototype.era\nand Temporal.PlainDate.prototype.monthCode\ndocs provide more information about different calendars.\nReferences:\n- CLDR Calendar type keys\n- UTS 35, Dates\n- Islamic calendar types (CLDR design proposal)\nSupported collation types\nBelow are all values that are commonly supported by browsers for the collation\nkey. These values can be used for the collation\noption or the co\nUnicode extension key when creating objects such as Intl.Collator\n.\n| Value | Description |\n|---|---|\ncompat |\nA previous version of the ordering, for compatibility (for Arabic) |\ndict |\nDictionary style ordering (such as in Sinhala). Also recognized as dictionary . |\nemoji |\nRecommended ordering for emoji characters |\neor |\nEuropean ordering rules |\nphonebk |\nPhonebook style ordering (such as in German). Also recognized as phonebook . |\nphonetic |\nPhonetic ordering (sorting based on pronunciation; for Lingala) |\npinyin |\nPinyin ordering for Latin and for CJK characters (used in Chinese) |\nsearchjl |\nSpecial 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\" . |\nstroke |\nPinyin ordering for Latin, stroke order for CJK characters (used in Chinese) |\ntrad |\nTraditional style ordering (such as in Spanish). Also recognized as traditional . |\nunihan |\nPinyin ordering for Latin, Unihan radical-stroke ordering for CJK characters (used in Chinese) |\nzhuyin |\nPinyin ordering for Latin, zhuyin order for Bopomofo and CJK characters (used in Chinese) |\nThe 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:\n| Value | Description | Notes |\n|---|---|---|\nbig5han\nDeprecated\n|\nPinyin ordering for Latin, big5 charset ordering for CJK characters (used in Chinese) | Deprecated. |\ndirect\nDeprecated\n|\nBinary code point order (used in Hindi) | Deprecated. |\nducet |\nThe default Unicode collation element table order | The ducet collation type is not available to the Web. |\ngb2312\nDeprecated\n|\nPinyin ordering for Latin, gb2312han charset ordering for CJK characters (for Chinese). Also recognized as gb2312han . |\nDeprecated. |\nreformed\nDeprecated\n|\nReformed 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 . |\nsearch |\nSpecial 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. |\nstandard |\nDefault 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. |\nReferences:\nSupported currency identifiers\nCurrency identifiers are three-letter uppercase codes defined in ISO 4217. These values can be used for the currency\noption when creating objects such as Intl.NumberFormat\n, as well as for Intl.DisplayNames.prototype.of()\n. 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.\nReferences:\nSupported numbering system types\nBelow are all values that are commonly supported by browsers for the numberingSystem\nkey. These values can be used for the numberingSystem\noption or the nu\nUnicode extension key when creating objects such as Intl.NumberFormat\n. 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.\n| Value | Description | Digit characters |\n|---|---|---|\nadlm |\nAdlam digits | \ud83a\udd50\ud83a\udd51\ud83a\udd52\ud83a\udd53\ud83a\udd54\ud83a\udd55\ud83a\udd56\ud83a\udd57\ud83a\udd58\ud83a\udd59 (U+1E950 to U+1E959) |\nahom |\nAhom digits | \ud805\udf30\ud805\udf31\ud805\udf32\ud805\udf33\ud805\udf34\ud805\udf35\ud805\udf36\ud805\udf37\ud805\udf38\ud805\udf39 (U+11730 to U+11739) |\narab |\nArabic-Indic digits | \u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669 (U+0660 to U+0669) |\narabext |\nExtended Arabic-Indic digits | \u06f0\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9 (U+06F0 to U+06F9) |\narmn |\nArmenian upper case numerals | algorithmic |\narmnlow |\nArmenian lower case numerals | algorithmic |\nbali |\nBalinese digits | \u1b50\u1b51\u1b52\u1b53\u1b54\u1b55\u1b56\u1b57\u1b58\u1b59 (U+1B50 to U+1B59) |\nbeng |\nBengali digits | \u09e6\u09e7\u09e8\u09e9\u09ea\u09eb\u09ec\u09ed\u09ee\u09ef (U+09E6 to U+09EF) |\nbhks |\nBhaiksuki digits | \ud807\udc50\ud807\udc51\ud807\udc52\ud807\udc53\ud807\udc54\ud807\udc55\ud807\udc56\ud807\udc57\ud807\udc58\ud807\udc59 (U+11C50 to U+11C59) |\nbrah |\nBrahmi digits | \ud804\udc66\ud804\udc67\ud804\udc68\ud804\udc69\ud804\udc6a\ud804\udc6b\ud804\udc6c\ud804\udc6d\ud804\udc6e\ud804\udc6f (U+11066 to U+1106F) |\ncakm |\nChakma digits | \ud804\udd36\ud804\udd37\ud804\udd38\ud804\udd39\ud804\udd3a\ud804\udd3b\ud804\udd3c\ud804\udd3d\ud804\udd3e\ud804\udd3f (U+11136 to U+1113F) |\ncham |\nCham digits | \uaa50\uaa51\uaa52\uaa53\uaa54\uaa55\uaa56\uaa57\uaa58\uaa59 (U+AA50 to U+AA59) |\ncyrl |\nCyrillic numerals | algorithmic |\ndeva |\nDevanagari digits | \u0966\u0967\u0968\u0969\u096a\u096b\u096c\u096d\u096e\u096f (U+0966 to U+096F) |\ndiak |\nDives Akuru digits | \ud806\udd50\ud806\udd51\ud806\udd52\ud806\udd53\ud806\udd54\ud806\udd55\ud806\udd56\ud806\udd57\ud806\udd58\ud806\udd59 (U+11950 to U+11959) |\nethi |\nEthiopic numerals | algorithmic |\nfullwide |\nFull width digits | \uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19 (U+FF10 to U+FF19) |\ngara |\nGaray digits | (U+10D40 to U+10D49) |\ngeor |\nGeorgian numerals | algorithmic |\ngong |\nGunjala Gondi digits | \ud807\udda0\ud807\udda1\ud807\udda2\ud807\udda3\ud807\udda4\ud807\udda5\ud807\udda6\ud807\udda7\ud807\udda8\ud807\udda9 (U+11DA0 to U+11DA9) |\ngonm |\nMasaram Gondi digits | \ud807\udd50\ud807\udd51\ud807\udd52\ud807\udd53\ud807\udd54\ud807\udd55\ud807\udd56\ud807\udd57\ud807\udd58\ud807\udd59 (U+11D50 to U+11D59) |\ngrek |\nGreek upper case numerals | algorithmic |\ngreklow |\nGreek lower case numerals | algorithmic |\ngujr |\nGujarati digits | \u0ae6\u0ae7\u0ae8\u0ae9\u0aea\u0aeb\u0aec\u0aed\u0aee\u0aef (U+0AE6 to U+0AEF) |\ngukh |\nGurung Khema digits | (U+16130 to U+16139) |\nguru |\nGurmukhi digits | \u0a66\u0a67\u0a68\u0a69\u0a6a\u0a6b\u0a6c\u0a6d\u0a6e\u0a6f (U+0A66 to U+0A6F) |\nhanidays |\nHan-character day-of-month numbering for lunar/other traditional calendars | |\nhanidec |\nPositional decimal system using Chinese number ideographs as digits | \u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d (U+3007, U+4E00, U+4E8C, U+4E09, U+56DB, U+4E94, U+516D, U+4E03, U+516B, U+4E5D) |\nhans |\nSimplified Chinese numerals | algorithmic |\nhansfin |\nSimplified Chinese financial numerals | algorithmic |\nhant |\nTraditional Chinese numerals | algorithmic |\nhantfin |\nTraditional Chinese financial numerals | algorithmic |\nhebr |\nHebrew numerals | algorithmic |\nhmng |\nPahawh Hmong digits | \ud81a\udf50\ud81a\udf51\ud81a\udf52\ud81a\udf53\ud81a\udf54\ud81a\udf55\ud81a\udf56\ud81a\udf57\ud81a\udf58\ud81a\udf59 (U+16B50 to U+16B59) |\nhmnp |\nNyiakeng Puachue Hmong digits | \ud838\udd40\ud838\udd41\ud838\udd42\ud838\udd43\ud838\udd44\ud838\udd45\ud838\udd46\ud838\udd47\ud838\udd48\ud838\udd49 (U+1E140 to U+1E149) |\njava |\nJavanese digits | \ua9d0\ua9d1\ua9d2\ua9d3\ua9d4\ua9d5\ua9d6\ua9d7\ua9d8\ua9d9 (U+A9D0 to U+A9D9) |\njpan |\nJapanese numerals | algorithmic |\njpanfin |\nJapanese financial numerals | algorithmic |\njpanyear |\nJapanese first-year Gannen numbering for Japanese calendar | algorithmic |\nkali |\nKayah Li digits | \ua900\ua901\ua902\ua903\ua904\ua905\ua906\ua907\ua908\ua909 (U+A900 to U+A909) |\nkawi |\nKawi digits | \ud807\udf50\ud807\udf51\ud807\udf52\ud807\udf53\ud807\udf54\ud807\udf55\ud807\udf56\ud807\udf57\ud807\udf58\ud807\udf59 (U+11F50 to U+11F59) |\nkhmr |\nKhmer digits | \u17e0\u17e1\u17e2\u17e3\u17e4\u17e5\u17e6\u17e7\u17e8\u17e9 (U+17E0 to U+17E9) |\nknda |\nKannada digits | \u0ce6\u0ce7\u0ce8\u0ce9\u0cea\u0ceb\u0cec\u0ced\u0cee\u0cef (U+0CE6 to U+0CEF) |\nkrai |\nKirat Rai digits | (U+16D70 to U+16D79) |\nlana |\nTai Tham Hora (secular) digits | \u1a80\u1a81\u1a82\u1a83\u1a84\u1a85\u1a86\u1a87\u1a88\u1a89 (U+1A80 to U+1A89) |\nlanatham |\nTai Tham (ecclesiastical) digits | \u1a90\u1a91\u1a92\u1a93\u1a94\u1a95\u1a96\u1a97\u1a98\u1a99 (U+1A90 to U+1A99) |\nlaoo |\nLao digits | \u0ed0\u0ed1\u0ed2\u0ed3\u0ed4\u0ed5\u0ed6\u0ed7\u0ed8\u0ed9 (U+0ED0 to U+0ED9) |\nlatn |\nLatin digits | 0123456789 (U+0030 to U+0039) |\nlepc |\nLepcha digits | \u1c40\u1c41\u1c42\u1c43\u1c44\u1c45\u1c46\u1c47\u1c48\u1c49 (U+1C40 to U+1C49) |\nlimb |\nLimbu digits | \u1946\u1947\u1948\u1949\u194a\u194b\u194c\u194d\u194e\u194f (U+1946 to U+194F) |\nmathbold |\nMathematical bold digits | \ud835\udfce\ud835\udfcf\ud835\udfd0\ud835\udfd1\ud835\udfd2\ud835\udfd3\ud835\udfd4\ud835\udfd5\ud835\udfd6\ud835\udfd7 (U+1D7CE to U+1D7D7) |\nmathdbl |\nMathematical double-struck digits | \ud835\udfd8\ud835\udfd9\ud835\udfda\ud835\udfdb\ud835\udfdc\ud835\udfdd\ud835\udfde\ud835\udfdf\ud835\udfe0\ud835\udfe1 (U+1D7D8 to U+1D7E1) |\nmathmono |\nMathematical monospace digits | \ud835\udff6\ud835\udff7\ud835\udff8\ud835\udff9\ud835\udffa\ud835\udffb\ud835\udffc\ud835\udffd\ud835\udffe\ud835\udfff (U+1D7F6 to U+1D7FF) |\nmathsanb |\nMathematical sans-serif bold digits | \ud835\udfec\ud835\udfed\ud835\udfee\ud835\udfef\ud835\udff0\ud835\udff1\ud835\udff2\ud835\udff3\ud835\udff4\ud835\udff5 (U+1D7EC to U+1D7F5) |\nmathsans |\nMathematical sans-serif digits | \ud835\udfe2\ud835\udfe3\ud835\udfe4\ud835\udfe5\ud835\udfe6\ud835\udfe7\ud835\udfe8\ud835\udfe9\ud835\udfea\ud835\udfeb (U+1D7E2 to U+1D7EB) |\nmlym |\nMalayalam digits | \u0d66\u0d67\u0d68\u0d69\u0d6a\u0d6b\u0d6c\u0d6d\u0d6e\u0d6f (U+0D66 to U+0D6F) |\nmodi |\nModi digits | \ud805\ude50\ud805\ude51\ud805\ude52\ud805\ude53\ud805\ude54\ud805\ude55\ud805\ude56\ud805\ude57\ud805\ude58\ud805\ude59 (U+11650 to U+11659) |\nmong |\nMongolian digits | \u1810\u1811\u1812\u1813\u1814\u1815\u1816\u1817\u1818\u1819 (U+1810 to U+1819) |\nmroo |\nMro digits | \ud81a\ude60\ud81a\ude61\ud81a\ude62\ud81a\ude63\ud81a\ude64\ud81a\ude65\ud81a\ude66\ud81a\ude67\ud81a\ude68\ud81a\ude69 (U+16A60 to U+16A69) |\nmtei |\nMeetei Mayek digits | \uabf0\uabf1\uabf2\uabf3\uabf4\uabf5\uabf6\uabf7\uabf8\uabf9 (U+ABF0 to U+ABF9) |\nmymr |\nMyanmar digits | \u1040\u1041\u1042\u1043\u1044\u1045\u1046\u1047\u1048\u1049 (U+1040 to U+1049) |\nmymrepka |\nMyanmar Eastern Pwo Karen digits | (U+116DA to U+116E3) |\nmymrpao |\nMyanmar Pao digits | (U+116D0 to U+116D9) |\nmymrshan |\nMyanmar Shan digits | \u1090\u1091\u1092\u1093\u1094\u1095\u1096\u1097\u1098\u1099 (U+1090 to U+1099) |\nmymrtlng |\nMyanmar Tai Laing digits | \ua9f0\ua9f1\ua9f2\ua9f3\ua9f4\ua9f5\ua9f6\ua9f7\ua9f8\ua9f9 (U+A9F0 to U+A9F9) |\nnagm |\nNag Mundari digits | \ud839\udcf0\ud839\udcf1\ud839\udcf2\ud839\udcf3\ud839\udcf4\ud839\udcf5\ud839\udcf6\ud839\udcf7\ud839\udcf8\ud839\udcf9 (U+1E4F0 to U+1E4F9) |\nnewa |\nNewa digits | \ud805\udc50\ud805\udc51\ud805\udc52\ud805\udc53\ud805\udc54\ud805\udc55\ud805\udc56\ud805\udc57\ud805\udc58\ud805\udc59 (U+11450 to U+11459) |\nnkoo |\nN'Ko digits | \u07c0\u07c1\u07c2\u07c3\u07c4\u07c5\u07c6\u07c7\u07c8\u07c9 (U+07C0 to U+07C9) |\nolck |\nOl Chiki digits | \u1c50\u1c51\u1c52\u1c53\u1c54\u1c55\u1c56\u1c57\u1c58\u1c59 (U+1C50 to U+1C59) |\nonao |\nOl Onal digits | (U+1E5F1 to U+1E5FA) |\norya |\nOriya digits | \u0b66\u0b67\u0b68\u0b69\u0b6a\u0b6b\u0b6c\u0b6d\u0b6e\u0b6f (U+0B66 to U+0B6F) |\nosma |\nOsmanya digits | \ud801\udca0\ud801\udca1\ud801\udca2\ud801\udca3\ud801\udca4\ud801\udca5\ud801\udca6\ud801\udca7\ud801\udca8\ud801\udca9 (U+104A0 to U+104A9) |\noutlined |\nLegacy computing outlined digits | (U+1CCF0 to U+1CCF9) |\nrohg |\nHanifi Rohingya digits | \ud803\udd30\ud803\udd31\ud803\udd32\ud803\udd33\ud803\udd34\ud803\udd35\ud803\udd36\ud803\udd37\ud803\udd38\ud803\udd39 (U+10D30 to U+10D39) |\nroman |\nRoman upper case numerals | algorithmic |\nromanlow |\nRoman lowercase numerals | algorithmic |\nsaur |\nSaurashtra digits | \ua8d0\ua8d1\ua8d2\ua8d3\ua8d4\ua8d5\ua8d6\ua8d7\ua8d8\ua8d9 (U+A8D0 to U+A8D9) |\nsegment |\nLegacy computing segmented digits | \ud83e\udff0\ud83e\udff1\ud83e\udff2\ud83e\udff3\ud83e\udff4\ud83e\udff5\ud83e\udff6\ud83e\udff7\ud83e\udff8\ud83e\udff9 (U+1FBF0 to U+1FBF9) |\nshrd |\nSharada digits | \ud804\uddd0\ud804\uddd1\ud804\uddd2\ud804\uddd3\ud804\uddd4\ud804\uddd5\ud804\uddd6\ud804\uddd7\ud804\uddd8\ud804\uddd9 (U+111D0 to U+111D9) |\nsind |\nKhudawadi digits | \ud804\udef0\ud804\udef1\ud804\udef2\ud804\udef3\ud804\udef4\ud804\udef5\ud804\udef6\ud804\udef7\ud804\udef8\ud804\udef9 (U+112F0 to U+112F9) |\nsinh |\nSinhala Lith digits | \u0de6\u0de7\u0de8\u0de9\u0dea\u0deb\u0dec\u0ded\u0dee\u0def (U+0DE6 to U+0DEF) |\nsora |\nSora_Sompeng digits | \ud804\udcf0\ud804\udcf1\ud804\udcf2\ud804\udcf3\ud804\udcf4\ud804\udcf5\ud804\udcf6\ud804\udcf7\ud804\udcf8\ud804\udcf9 (U+110F0 to U+110F9) |\nsund |\nSundanese digits | \u1bb0\u1bb1\u1bb2\u1bb3\u1bb4\u1bb5\u1bb6\u1bb7\u1bb8\u1bb9 (U+1BB0 to U+1BB9) |\nsunu |\nSunuwar digits | (U+11BF0 to U+11BF9) |\ntakr |\nTakri digits | \ud805\udec0\ud805\udec1\ud805\udec2\ud805\udec3\ud805\udec4\ud805\udec5\ud805\udec6\ud805\udec7\ud805\udec8\ud805\udec9 (U+116C0 to U+116C9) |\ntalu |\nNew Tai Lue digits | \u19d0\u19d1\u19d2\u19d3\u19d4\u19d5\u19d6\u19d7\u19d8\u19d9 (U+19D0 to U+19D9) |\ntaml |\nTamil numerals | algorithmic |\ntamldec |\nModern Tamil decimal digits | \u0be6\u0be7\u0be8\u0be9\u0bea\u0beb\u0bec\u0bed\u0bee\u0bef (U+0BE6 to U+0BEF) |\ntelu |\nTelugu digits | \u0c66\u0c67\u0c68\u0c69\u0c6a\u0c6b\u0c6c\u0c6d\u0c6e\u0c6f (U+0C66 to U+0C6F) |\nthai |\nThai digits | \u0e50\u0e51\u0e52\u0e53\u0e54\u0e55\u0e56\u0e57\u0e58\u0e59 (U+0E50 to U+0E59) |\ntibt |\nTibetan digits | \u0f20\u0f21\u0f22\u0f23\u0f24\u0f25\u0f26\u0f27\u0f28\u0f29 (U+0F20 to U+0F29) |\ntirh |\nTirhuta digits | \ud805\udcd0\ud805\udcd1\ud805\udcd2\ud805\udcd3\ud805\udcd4\ud805\udcd5\ud805\udcd6\ud805\udcd7\ud805\udcd8\ud805\udcd9 (U+114D0 to U+114D9) |\ntnsa |\nTangsa digits | \ud81a\udec0\ud81a\udec1\ud81a\udec2\ud81a\udec3\ud81a\udec4\ud81a\udec5\ud81a\udec6\ud81a\udec7\ud81a\udec8\ud81a\udec9 (U+16AC0 to U+16AC9) |\nvaii |\nVai digits | \ua620\ua621\ua622\ua623\ua624\ua625\ua626\ua627\ua628\ua629 (U+A620 to U+A629) |\nwara |\nWarang Citi digits | \ud806\udce0\ud806\udce1\ud806\udce2\ud806\udce3\ud806\udce4\ud806\udce5\ud806\udce6\ud806\udce7\ud806\udce8\ud806\udce9 (U+118E0 to U+118E9) |\nwcho |\nWancho digits | \ud838\udef0\ud838\udef1\ud838\udef2\ud838\udef3\ud838\udef4\ud838\udef5\ud838\udef6\ud838\udef7\ud838\udef8\ud838\udef9 (U+1E2F0 to U+1E2F9) |\nThere are three special values: native\n, traditio\n, and finance\n, whose meanings are locale-dependent, and will be resolved to the right system depending on the locale. Therefore, the resolvedOptions()\nmethods will never return these values, but Intl.Locale.prototype.numberingSystem\nwill (if provided as input).\nReferences:\nSupported time zone identifiers\nSupported time zone identifiers can be used for the timeZone\noption when creating objects such as Intl.DateTimeFormat\n, as well as for creating Temporal\ndate 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.\nAs you browse the list, note that the standardization of Temporal\nrequires 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\"\ninstead of \"Asia/Calcutta\"\nbecause the latter is an alias of the former and they both correspond to India; however, it should contain both \"Africa/Abidjan\"\nand \"Atlantic/Reykjavik\"\nbecause they are in different countries, despite the latter also being an alias of the former.\nReferences:\nSupported unit identifiers\nBelow are all values that are commonly supported by browsers for the unit\nkey. These values can be used for the unit\noption when creating objects such as Intl.NumberFormat\n. This list is a subset of the CLDR explicitly sanctioned by the ECMA-402 specification, so all implementations should be consistent.\nacre\nbit\nbyte\ncelsius\ncentimeter\nday\ndegree\nfahrenheit\nfluid-ounce\nfoot\ngallon\ngigabit\ngigabyte\ngram\nhectare\nhour\ninch\nkilobit\nkilobyte\nkilogram\nkilometer\nliter\nmegabit\nmegabyte\nmeter\nmicrosecond\nmile\nmile-scandinavian\nmilliliter\nmillimeter\nmillisecond\nminute\nmonth\nnanosecond\nounce\npercent\npetabyte\npound\nsecond\nstone\nterabit\nterabyte\nweek\nyard\nyear\nWhen specifying units, you can also combine two units with the \"-per-\" separator. For example, meter-per-second\nor liter-per-megabyte\n.\nReferences:\nExceptions\nRangeError\n-\nThrown if an unsupported key was passed as a parameter.\nExamples\nFeature testing\nYou can check that the method is supported by comparing to undefined\n:\nif (typeof Intl.supportedValuesOf !== \"undefined\") {\n// method is supported\n}\nGet all values for key\nTo get the supported values for calendar you call the method with the key \"calendar\"\n.\nYou can then iterate through the returned array as shown below:\nIntl.supportedValuesOf(\"calendar\").forEach((calendar) => {\n// \"buddhist\", \"chinese\", \"coptic\", \"dangi\", etc.\n});\nThe other values are all obtained in the same way:\nIntl.supportedValuesOf(\"collation\").forEach((collation) => {\n// \"compat\", \"dict\", \"emoji\", etc.\n});\nIntl.supportedValuesOf(\"currency\").forEach((currency) => {\n// \"ADP\", \"AED\", \"AFA\", \"AFN\", \"ALK\", \"ALL\", \"AMD\", etc.\n});\nIntl.supportedValuesOf(\"numberingSystem\").forEach((numberingSystem) => {\n// \"adlm\", \"ahom\", \"arab\", \"arabext\", \"bali\", etc.\n});\nIntl.supportedValuesOf(\"timeZone\").forEach((timeZone) => {\n// \"Africa/Abidjan\", \"Africa/Accra\", \"Africa/Addis_Ababa\", \"Africa/Algiers\", etc.\n});\nIntl.supportedValuesOf(\"unit\").forEach((unit) => {\n// \"acre\", \"bit\", \"byte\", \"celsius\", \"centimeter\", etc.\n});\nInvalid key throws RangeError\ntry {\nIntl.supportedValuesOf(\"someInvalidKey\");\n} catch (err) {\n// RangeError: invalid key: \"someInvalidKey\"\n}\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # sec-intl.supportedvaluesof |", "code_snippets": ["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"], "language": "JavaScript", "source": "mdn", "token_count": 5609} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/pluralrules/index.md\n\n# Original Wiki contributors\nlonglho\nmfuji09\nfscholz\nsideshowbarker\nbattaglr\nshvaikalesh\njpmedley\nTagir-A\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 65} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY", "title": "Number.POSITIVE_INFINITY", "content": "Number.POSITIVE_INFINITY\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe Number.POSITIVE_INFINITY\nstatic data property represents the positive Infinity value.\nTry it\nfunction checkNumber(bigNumber) {\nif (bigNumber === Number.POSITIVE_INFINITY) {\nreturn \"Process number as Infinity\";\n}\nreturn bigNumber;\n}\nconsole.log(checkNumber(Number.MAX_VALUE));\n// Expected output: 1.7976931348623157e+308\nconsole.log(checkNumber(Number.MAX_VALUE * 2));\n// Expected output: \"Process number as Infinity\"\nValue\nThe same as the value of the global Infinity\nproperty.\nProperty attributes of Number.POSITIVE_INFINITY | |\n|---|---|\n| Writable | no |\n| Enumerable | no |\n| Configurable | no |\nDescription\nThe Number.POSITIVE_INFINITY\nvalue behaves slightly differently than mathematical infinity:\n- Any positive value, including\nPOSITIVE_INFINITY\n, multiplied byPOSITIVE_INFINITY\nisPOSITIVE_INFINITY\n. - Any negative value, including\nNEGATIVE_INFINITY\n, multiplied byPOSITIVE_INFINITY\nisNEGATIVE_INFINITY\n. - Any positive number divided by\nPOSITIVE_INFINITY\nis positive zero (as defined in IEEE 754). - Any negative number divided by\nPOSITIVE_INFINITY\nis negative zero (as defined in IEEE 754. - Zero multiplied by\nPOSITIVE_INFINITY\nisNaN\n. NaN\nmultiplied byPOSITIVE_INFINITY\nisNaN\n.POSITIVE_INFINITY\n, divided by any negative value exceptNEGATIVE_INFINITY\n, isNEGATIVE_INFINITY\n.POSITIVE_INFINITY\n, divided by any positive value exceptPOSITIVE_INFINITY\n, isPOSITIVE_INFINITY\n.POSITIVE_INFINITY\n, divided by eitherNEGATIVE_INFINITY\norPOSITIVE_INFINITY\n, isNaN\n.Number.POSITIVE_INFINITY > x\nis true for any number x that isn'tPOSITIVE_INFINITY\n.\nYou might use the Number.POSITIVE_INFINITY\nproperty to indicate an error condition that returns a finite number in case of success. Note, however, that NaN\nwould be more appropriate in such a case.\nBecause POSITIVE_INFINITY\nis a static property of Number\n, you always use it as Number.POSITIVE_INFINITY\n, rather than as a property of a number value.\nExamples\nUsing POSITIVE_INFINITY\nIn the following example, the variable bigNumber\nis assigned a value that is larger than the maximum value. When the if\nstatement executes, bigNumber\nhas the value Infinity\n, so bigNumber\nis set to a more manageable value before continuing.\nlet bigNumber = Number.MAX_VALUE * 2;\nif (bigNumber === Number.POSITIVE_INFINITY) {\nbigNumber = returnFinite();\n}\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-number.positive_infinity |", "code_snippets": ["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"], "language": "JavaScript", "source": "mdn", "token_count": 762} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining", "title": "Optional chaining (?.)", "content": "Optional chaining (?.)\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2020.\nThe optional chaining (?.\n) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined\nor null\n, the expression short circuits and evaluates to undefined\ninstead of throwing an error.\nTry it\nconst adventurer = {\nname: \"Alice\",\ncat: {\nname: \"Dinah\",\n},\n};\nconst dogName = adventurer.dog?.name;\nconsole.log(dogName);\n// Expected output: undefined\nconsole.log(adventurer.someNonExistentMethod?.());\n// Expected output: undefined\nSyntax\nobj?.prop\nobj?.[expr]\nfunc?.(args)\nDescription\nThe ?.\noperator is like the .\nchaining operator, except that instead of causing an error if a reference is nullish (null\nor undefined\n), the expression short-circuits with a return value of undefined\n. When used with function calls, it returns undefined\nif the given function does not exist.\nThis 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.\nFor example, consider an object obj\nwhich has a nested structure. Without\noptional chaining, looking up a deeply-nested subproperty requires validating the\nreferences in between, such as:\nconst nestedProp = obj.first && obj.first.second;\nThe value of obj.first\nis confirmed to be non-null\n(and\nnon-undefined\n) before accessing the value of\nobj.first.second\n. This prevents the error that would occur if you accessed\nobj.first.second\ndirectly without testing obj.first\n.\nThis 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\nis a Falsy value that's not null\nor undefined\n, such as 0\n, it would still short-circuit and make nestedProp\nbecome 0\n, which may not be desirable.\nWith the optional chaining operator (?.\n), however, you don't have to\nexplicitly test and short-circuit based on the state of obj.first\nbefore\ntrying to access obj.first.second\n:\nconst nestedProp = obj.first?.second;\nBy using the ?.\noperator instead of just .\n, JavaScript knows\nto implicitly check to be sure obj.first\nis not null\nor\nundefined\nbefore attempting to access obj.first.second\n. If\nobj.first\nis null\nor undefined\n, the expression\nautomatically short-circuits, returning undefined\n.\nThis is equivalent to the following, except that the temporary variable is in fact not created:\nconst temp = obj.first;\nconst nestedProp =\ntemp === null || temp === undefined ? undefined : temp.second;\nOptional chaining cannot be used on a non-declared root object, but can be used with a root object with value undefined\n.\nundeclaredVar?.prop; // ReferenceError: undeclaredVar is not defined\nOptional chaining with function calls\nYou 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.\nUsing optional chaining with function calls causes the expression to automatically\nreturn undefined\ninstead of throwing an exception if the method isn't\nfound:\nconst result = someInterface.customMethod?.();\nHowever, if there is a property with such a name which is not a function, using ?.\nwill still raise a TypeError\nexception \"someInterface.customMethod is not a function\".\nNote:\nIf someInterface\nitself is null\nor\nundefined\n, a TypeError\nexception will still be\nraised (\"someInterface is null\"). If you expect that\nsomeInterface\nitself may be null\nor undefined\n,\nyou have to use ?.\nat this position as\nwell: someInterface?.customMethod?.()\n.\neval?.()\nis the shortest way to enter indirect eval mode.\nOptional chaining with expressions\nYou can also use the optional chaining operator with bracket notation, which allows passing an expression as the property name:\nconst propName = \"x\";\nconst nestedProp = obj?.[propName];\nThis is particularly useful for arrays, since array indices must be accessed with square brackets.\nfunction printMagicIndex(arr) {\nconsole.log(arr?.[42]);\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')\"\nInvalid optional chaining\nIt is invalid to try to assign to the result of an optional chaining expression:\nconst object = {};\nobject?.property = 1; // SyntaxError: Invalid left-hand side in assignment\nTemplate literal tags cannot be an optional chain (see SyntaxError: tagged template cannot be used with optional chain):\nString?.raw`Hello, world!`;\nString.raw?.`Hello, world!`; // SyntaxError: Invalid tagged template on optional chain\nThe constructor of new\nexpressions cannot be an optional chain (see SyntaxError: new keyword cannot be used with an optional chain):\nnew Intl?.DateTimeFormat(); // SyntaxError: Invalid optional chain from new expression\nnew Map?.();\nShort-circuiting\nWhen using optional chaining with expressions, if the left operand is null\nor undefined\n, the expression will not be evaluated. For instance:\nconst potentiallyNullObj = null;\nlet x = 0;\nconst prop = potentiallyNullObj?.[x++];\nconsole.log(x); // 0 as x was not incremented\nSubsequent property accesses will not be evaluated either.\nconst potentiallyNullObj = null;\nconst prop = potentiallyNullObj?.a.b;\n// This does not throw, because evaluation has already stopped at\n// the first optional chain\nThis is equivalent to:\nconst potentiallyNullObj = null;\nconst prop =\npotentiallyNullObj === null || potentiallyNullObj === undefined\n? undefined\n: potentiallyNullObj.a.b;\nHowever, 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.\nconst potentiallyNullObj = null;\nconst prop = (potentiallyNullObj?.a).b;\n// TypeError: Cannot read properties of undefined (reading 'b')\nThis is equivalent to:\nconst potentiallyNullObj = null;\nconst temp = potentiallyNullObj?.a;\nconst prop = temp.b;\nExcept the temp\nvariable isn't created.\nExamples\nBasic example\nThis example looks for the value of the name\nproperty for the member\nCSS\nin a map when there is no such member. The result is therefore\nundefined\n.\nconst myMap = new Map();\nmyMap.set(\"JS\", { name: \"Josh\", desc: \"I maintain things\" });\nconst nameBar = myMap.get(\"CSS\")?.name;\nDealing with optional callbacks or event handlers\nIf you use callbacks or fetch methods from an object with a\ndestructuring pattern, you may have non-existent values that you cannot call as\nfunctions unless you have tested their existence. Using ?.\n, you can avoid this extra test:\n// Code written without optional chaining\nfunction doSomething(onContent, onError) {\ntry {\n// Do something with the data\n} catch (err) {\n// Testing if onError really exists\nif (onError) {\nonError(err.message);\n}\n}\n}\n// Using optional chaining with function calls\nfunction doSomething(onContent, onError) {\ntry {\n// Do something with the data\n} catch (err) {\nonError?.(err.message); // No exception if onError is undefined\n}\n}\nStacking the optional chaining operator\nWith nested structures, it is possible to use optional chaining multiple times:\nconst customer = {\nname: \"Carl\",\ndetails: {\nage: 82,\nlocation: \"Paradise Falls\", // Detailed address is unknown\n},\n};\nconst customerCity = customer.details?.address?.city;\n// This also works with optional chaining function call\nconst customerName = customer.name?.getName?.(); // Method does not exist, customerName is undefined\nCombining with the nullish coalescing operator\nThe nullish coalescing operator may be used after optional chaining in order to build a default value when none was found:\nfunction printCustomerCity(customer) {\nconst customerCity = customer?.city ?? \"Unknown city\";\nconsole.log(customerCity);\n}\nprintCustomerCity({\nname: \"Nathan\",\ncity: \"Paris\",\n}); // \"Paris\"\nprintCustomerCity({\nname: \"Carl\",\ndetails: { age: 82 },\n}); // \"Unknown city\"\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # prod-OptionalExpression |", "code_snippets": ["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"], "language": "JavaScript", "source": "mdn", "token_count": 2871} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat", "title": "Intl.DateTimeFormat() constructor", "content": "Intl.DateTimeFormat() constructor\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since September 2017.\nThe Intl.DateTimeFormat()\nconstructor creates Intl.DateTimeFormat\nobjects.\nTry it\nconst date = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));\n// Results below assume UTC timezone - your results may vary\n// Specify default date formatting for language (locale)\nconsole.log(new Intl.DateTimeFormat(\"en-US\").format(date));\n// Expected output: \"12/20/2020\"\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// Specify date and time format using \"style\" options (i.e. full, long, medium, short)\nconsole.log(\nnew Intl.DateTimeFormat(\"en-GB\", {\ndateStyle: \"full\",\ntimeStyle: \"long\",\ntimeZone: \"Australia/Sydney\",\n}).format(date),\n);\n// Expected output: \"Sunday, 20 December 2020 at 14:23:16 GMT+11\"\nSyntax\nnew Intl.DateTimeFormat()\nnew Intl.DateTimeFormat(locales)\nnew Intl.DateTimeFormat(locales, options)\nIntl.DateTimeFormat()\nIntl.DateTimeFormat(locales)\nIntl.DateTimeFormat(locales, options)\nNote:\nIntl.DateTimeFormat()\ncan be called with or without new\n. Both create a new Intl.DateTimeFormat\ninstance. However, there's a special behavior when it's called without new\nand the this\nvalue is another Intl.DateTimeFormat\ninstance; see Return value.\nParameters\nlocales\nOptional-\nA string with a BCP 47 language tag or an\nIntl.Locale\ninstance, or an array of such locale identifiers. The runtime's default locale is used whenundefined\nis passed or when none of the specified locale identifiers is supported. For the general form and interpretation of thelocales\nargument, see the parameter description on theIntl\nmain page.The following Unicode extension keys are allowed:\nThese keys can also be set with\noptions\n(as listed below). When both are set, theoptions\nproperty takes precedence. options\nOptional-\nAn 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.\nLocale options\nlocaleMatcher\n-\nThe locale matching algorithm to use. Possible values are\n\"lookup\"\nand\"best fit\"\n; the default is\"best fit\"\n. For information about this option, see Locale identification and negotiation. calendar\n-\nThe calendar to use, such as\n\"chinese\"\n,\"gregory\"\n,\"persian\"\n, and so on. For a list of supported calendar types, seeIntl.supportedValuesOf()\n; the default is locale dependent. This option can also be set through theca\nUnicode extension key; if both are provided, thisoptions\nproperty takes precedence. numberingSystem\n-\nThe numbering system to use for number formatting, such as\n\"arab\"\n,\"hans\"\n,\"mathsans\"\n, and so on. For a list of supported numbering system types, seeIntl.supportedValuesOf()\n; the default is locale dependent. This option can also be set through thenu\nUnicode extension key; if both are provided, thisoptions\nproperty takes precedence. hour12\n-\nWhether to use 12-hour time (as opposed to 24-hour time). Possible values are\ntrue\nandfalse\n; the default is locale dependent. Whentrue\n, this option setshourCycle\nto either\"h11\"\nor\"h12\"\n, depending on the locale. Whenfalse\n, it setshourCycle\nto\"h23\"\n.hour12\noverrides both thehc\nlocale extension tag and thehourCycle\noption, should either or both of those be present. hourCycle\n-\nThe hour cycle to use. Possible values are\n\"h11\"\n,\"h12\"\n,\"h23\"\n, and\"h24\"\n; the default is inferred fromhour12\nand locale. This option can also be set through thehc\nUnicode extension key; if both are provided, thisoptions\nproperty takes precedence. timeZone\n-\nThe time zone to use. Can be any IANA time zone name, including named identifiers such as\n\"UTC\"\n,\"America/New_York\"\n, and\"Etc/GMT+8\"\n, and offset identifiers such as\"+01:00\"\n,\"-2359\"\n, and\"+23\"\n. The default is the runtime's time zone, the same time zone used byDate.prototype.toString()\n.\nDate-time component options\nweekday\n-\nThe representation of the weekday. Possible values are:\nera\n-\nThe representation of the era. Possible values are:\nyear\n-\nThe representation of the year. Possible values are\n\"numeric\"\nand\"2-digit\"\n. month\n-\nThe representation of the month. Possible values are:\nday\n-\nThe representation of the day. Possible values are\n\"numeric\"\nand\"2-digit\"\n. dayPeriod\n-\nThe formatting style used for day periods like \"in the morning\", \"am\", \"noon\", \"n\" etc. Possible values are\n\"narrow\"\n,\"short\"\n, and\"long\"\n.Note: This option only has an effect if a 12-hour clock (\nhourCycle: \"h12\"\norhourCycle: \"h11\"\n) is used. Many locales use the same string irrespective of the width specified. hour\n-\nThe representation of the hour. Possible values are\n\"numeric\"\nand\"2-digit\"\n. minute\n-\nThe representation of the minute. Possible values are\n\"numeric\"\nand\"2-digit\"\n. second\n-\nThe representation of the second. Possible values are\n\"numeric\"\nand\"2-digit\"\n. fractionalSecondDigits\n-\nThe number of digits used to represent fractions of a second (any additional digits are truncated). Possible values are from\n1\nto3\n. timeZoneName\n-\nThe localized representation of the time zone name. Possible values are:\n\"long\"\n-\nLong localized form (e.g.,\nPacific Standard Time\n,Nordamerikanische Westk\u00fcsten-Normalzeit\n) \"short\"\n-\nShort localized form (e.g.:\nPST\n,GMT-8\n) \"shortOffset\"\n-\nShort localized GMT format (e.g.,\nGMT-8\n) \"longOffset\"\n-\nLong localized GMT format (e.g.,\nGMT-08:00\n) \"shortGeneric\"\n-\nShort generic non-location format (e.g.:\nPT\n,Los Angeles Zeit\n). \"longGeneric\"\n-\nLong generic non-location format (e.g.:\nPacific Time\n,Nordamerikanische Westk\u00fcstenzeit\n)\nNote: 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\".\nDate-time component default values\nIf any of the date-time component options are specified, then dateStyle\nand timeStyle\nmust be undefined\n. If all date-time component options and dateStyle\n/timeStyle\nare undefined\n, some default options for date-time components are set, which depend on the object that the formatting method was called with:\n- When formatting\nTemporal.PlainDate\nandDate\n,year\n,month\n, andday\ndefault to\"numeric\"\n. - When formatting\nTemporal.PlainTime\n,hour\n,minute\n, andsecond\ndefault to\"numeric\"\n. - When formatting\nTemporal.PlainYearMonth\n,year\nandmonth\ndefault to\"numeric\"\n. - When formatting\nTemporal.PlainMonthDay\n,month\nandday\ndefault to\"numeric\"\n. - When formatting\nTemporal.PlainDateTime\nandTemporal.Instant\n,year\n,month\n,day\n,hour\n,minute\n, andsecond\ndefault to\"numeric\"\n.\nFormat matching\nImplementations are required to support displaying at least the following subsets of date-time components:\nweekday\n,year\n,month\n,day\n,hour\n,minute\n,second\nweekday\n,year\n,month\n,day\nyear\n,month\n,day\nyear\n,month\nmonth\n,day\nhour\n,minute\n,second\nhour\n,minute\nThe 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.\nformatMatcher\n-\nThe format matching algorithm to use. Possible values are\n\"basic\"\nand\"best fit\"\n; the default is\"best fit\"\n. The algorithm for\"best fit\"\nis implementation-defined, and\"basic\"\nis defined by the spec. This option is only used when bothdateStyle\nandtimeStyle\nareundefined\n(so that each date-time component's format is individually customizable).\nStyle shortcuts\ndateStyle\n-\nThe date formatting style to use. Possible values are\n\"full\"\n,\"long\"\n,\"medium\"\n, and\"short\"\n. It expands to styles forweekday\n,day\n,month\n,year\n, andera\n, with the exact combination of values depending on the locale. When formatting objects such asTemporal.PlainDate\n,Temporal.PlainYearMonth\n, andTemporal.PlainMonthDay\n,dateStyle\nwill resolve to only those fields relevant to the object. timeStyle\n-\nThe time formatting style to use. Possible values are\n\"full\"\n,\"long\"\n,\"medium\"\n, and\"short\"\n. It expands to styles forhour\n,minute\n,second\n, andtimeZoneName\n, with the exact combination of values depending on the locale.\nNote:\ndateStyle\nand timeStyle\ncan be used with each other, but not with other date-time component options (e.g., weekday\n, hour\n, month\n, etc.).\nYou can format different object types depending on which of the style shortcut options you include:\n- If the\ndateStyle\nis specified, then you can formatTemporal.PlainDate\n,Temporal.PlainYearMonth\n, andTemporal.PlainMonthDay\nobjects. - If the\ntimeStyle\nis specified, then you can formatTemporal.PlainTime\nobjects. - If either\ndateStyle\nortimeStyle\nis specified, then you can formatTemporal.PlainDateTime\nandDate\nobjects.\nReturn value\nA new Intl.DateTimeFormat\nobject.\nNote: 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.\nNormally, Intl.DateTimeFormat()\ncan be called with or without new\n, and a new Intl.DateTimeFormat\ninstance is returned in both cases. However, if the this\nvalue is an object that is instanceof\nIntl.DateTimeFormat\n(doesn't necessarily mean it's created via new Intl.DateTimeFormat\n; just that it has Intl.DateTimeFormat.prototype\nin its prototype chain), then the value of this\nis returned instead, with the newly created Intl.DateTimeFormat\nobject hidden in a [Symbol(IntlLegacyConstructedSymbol)]\nproperty (a unique symbol that's reused between instances).\nconst 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// }\nNote that there's only one actual Intl.DateTimeFormat\ninstance here: the one hidden in [Symbol(IntlLegacyConstructedSymbol)]\n. Calling the format()\nand resolvedOptions()\nmethods on formatter\nwould correctly use the options stored in that instance, but calling all other methods (e.g., formatRange()\n) would fail: \"TypeError: formatRange method called on incompatible Object\", because those methods don't consult the hidden instance's options.\nThis behavior, called ChainDateTimeFormat\n, does not happen when Intl.DateTimeFormat()\nis called without new\nbut with this\nset to anything else that's not an instanceof Intl.DateTimeFormat\n. If you call it directly as Intl.DateTimeFormat()\n, the this\nvalue is Intl\n, and a new Intl.DateTimeFormat\ninstance is created normally.\nExceptions\nRangeError\n-\nThrown if\nlocales\noroptions\ncontain invalid values.\nExamples\nUsing DateTimeFormat\nIn basic use without specifying a locale, DateTimeFormat\nuses the default\nlocale and default options.\nconst date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\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)\nUsing timeStyle and dateStyle\ndateStyle\nand timeStyle\nprovide a shortcut for setting multiple date-time component options at once. For example, for en-US\n, dateStyle: \"short\"\nis equivalent to setting year: \"2-digit\", month: \"numeric\", day: \"numeric\"\n, and timeStyle: \"short\"\nis equivalent to setting hour: \"numeric\", minute: \"numeric\"\n.\nconst shortTime = new Intl.DateTimeFormat(\"en-US\", {\ntimeStyle: \"short\",\n});\nconsole.log(shortTime.format(Date.now())); // \"1:31 PM\"\nconst shortDate = new Intl.DateTimeFormat(\"en-US\", {\ndateStyle: \"short\",\n});\nconsole.log(shortDate.format(Date.now())); // \"7/7/20\"\nconst mediumTime = new Intl.DateTimeFormat(\"en-US\", {\ntimeStyle: \"medium\",\ndateStyle: \"short\",\n});\nconsole.log(mediumTime.format(Date.now())); // \"7/7/20, 1:31:55 PM\"\nHowever, the exact (locale dependent) component styles they resolve to are not included in the resolved options. This ensures the result of resolvedOptions()\ncan be passed directly to the Intl.DateTimeFormat()\nconstructor (because an options\nobject with both dateStyle\nor timeStyle\nand individual date or time component styles is not valid).\nconsole.log(shortDate.resolvedOptions().year); // undefined\nUsing dayPeriod\nUse the dayPeriod\noption 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'\nor hourCycle: 'h11'\n) and that for many locales the strings are the same irrespective of the value passed for the dayPeriod\n.\nconst date = Date.UTC(2012, 11, 17, 4, 0, 42);\nconsole.log(\nnew Intl.DateTimeFormat(\"en-GB\", {\nhour: \"numeric\",\nhourCycle: \"h12\",\ndayPeriod: \"short\",\ntimeZone: \"UTC\",\n}).format(date),\n);\n// 4 at night\" (same formatting in en-GB for all dayPeriod values)\nconsole.log(\nnew Intl.DateTimeFormat(\"fr\", {\nhour: \"numeric\",\nhourCycle: \"h12\",\ndayPeriod: \"narrow\",\ntimeZone: \"UTC\",\n}).format(date),\n);\n// \"4 mat.\" (same output in French for both narrow/short dayPeriod)\nconsole.log(\nnew Intl.DateTimeFormat(\"fr\", {\nhour: \"numeric\",\nhourCycle: \"h12\",\ndayPeriod: \"long\",\ntimeZone: \"UTC\",\n}).format(date),\n);\n// \"4 du matin\"\nUsing timeZoneName\nUse the timeZoneName\noption to output a string for the timezone (\"GMT\", \"Pacific Time\", etc.).\nconst date = Date.UTC(2021, 11, 17, 3, 0, 42);\nconst timezoneNames = [\n\"short\",\n\"long\",\n\"shortOffset\",\n\"longOffset\",\n\"shortGeneric\",\n\"longGeneric\",\n];\nfor (const zoneName of timezoneNames) {\n// Do something with currentValue\nconst formatter = new Intl.DateTimeFormat(\"en-US\", {\ntimeZone: \"America/Los_Angeles\",\ntimeZoneName: zoneName,\n});\nconsole.log(`${zoneName}: ${formatter.format(date)}`);\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\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # sec-intl-datetimeformat-constructor |", "code_snippets": ["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"], "language": "JavaScript", "source": "mdn", "token_count": 4448} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Now/plainDateISO", "title": "Temporal.Now.plainDateISO()", "content": "Temporal.Now.plainDateISO()\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe Temporal.Now.plainDateISO()\nstatic method returns the current date as a Temporal.PlainDate\nobject, in the ISO 8601 calendar and the specified time zone.\nSyntax\nTemporal.Now.plainDateISO()\nTemporal.Now.plainDateISO(timeZone)\nParameters\ntimeZone\nOptional-\nEither a string or a\nTemporal.ZonedDateTime\ninstance representing the time zone to interpret the system time in. If aTemporal.ZonedDateTime\ninstance, 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).\nReturn value\nThe current date in the specified time zone, as a Temporal.PlainDate\nobject using the ISO 8601 calendar.\nExceptions\nRangeError\n-\nThrown if the time zone is invalid.\nExamples\nUsing Temporal.Now.plainDateISO()\n// The current date in the system's time zone\nconst date = Temporal.Now.plainDateISO();\nconsole.log(date); // e.g.: 2021-10-01\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\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-temporal.now.plaindateiso |", "code_snippets": ["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"], "language": "JavaScript", "source": "mdn", "token_count": 437} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality", "title": "Strict inequality (!==)", "content": "Strict inequality (!==)\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe strict inequality (!==\n) operator checks whether its two operands are\nnot equal, returning a Boolean result. Unlike the inequality\noperator, the strict inequality operator always considers operands of different types to\nbe different.\nTry it\nconsole.log(1 !== 1);\n// Expected output: false\nconsole.log(\"hello\" !== \"hello\");\n// Expected output: false\nconsole.log(\"1\" !== 1);\n// Expected output: true\nconsole.log(0 !== false);\n// Expected output: true\nSyntax\nx !== y\nDescription\nThe 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:\nx !== y;\n!(x === y);\nFor details of the comparison algorithm, see the page for the strict equality operator.\nLike the strict equality operator, the strict inequality operator will always consider operands of different types to be different:\n3 !== \"3\"; // true\nExamples\nComparing operands of the same type\n\"hello\" !== \"hello\"; // false\n\"hello\" !== \"hola\"; // true\n3 !== 3; // false\n3 !== 4; // true\ntrue !== true; // false\ntrue !== false; // true\nnull !== null; // false\nComparing operands of different types\n\"3\" !== 3; // true\ntrue !== 1; // true\nnull !== undefined; // true\nComparing objects\nconst object1 = {\nkey: \"value\",\n};\nconst object2 = {\nkey: \"value\",\n};\nconsole.log(object1 !== object2); // true\nconsole.log(object1 !== object1); // false\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-equality-operators |", "code_snippets": ["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"], "language": "JavaScript", "source": "mdn", "token_count": 591} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/description/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/symbol/description/index.md\n\n# Original Wiki contributors\nwbamberg\nfscholz\nddbeck\nsideshowbarker\nExE-Boss\nturtlemaster19\nLJHarb\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 64} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/asUintN/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/bigint/asuintn/index.md\n\n# Original Wiki contributors\nfscholz\nmfuji09\nwbamberg\nAnyhowStep\nsideshowbarker\nExE-Boss\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 60} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/lexical_grammar/index.md\n\n# Original Wiki contributors\niwhoisrishabh\nhinell\nwbamberg\nfscholz\nlucaswerkmeister\nneverRare\nLeonFrempong\nmfuji09\nAljullu\nrwaldron\njinbeomhong\nalattalatta\nNux\nchrisdavidmills\nirenesmith\nzhaoyingdu\nmyakura\nWaldo\nGSRyu\nErutuon\nmistoken\nnmve\nkdex\nlewisje\nfasttime\nPointy\nstevemao\nmichaelficarra\nmerih\nHywan\nakinjide\nKiraAndMaxim\nrealityking\njpmedley\nLoTD\nMinat\nPenny\njensen\nmorello\njscape\nRogerPoon\nshvaikalesh\nzzmp\nwilliampower\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 141} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/format/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/durationformat/format/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 41} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Key_not_weakly_held/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/errors/key_not_weakly_held/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 37} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Malformed_URI", "title": "URIError: malformed URI sequence", "content": "URIError: malformed URI sequence\nThe JavaScript exception \"malformed URI sequence\" occurs when URI encoding or decoding wasn't successful.\nMessage\nURIError: URI malformed (V8-based) URIError: malformed URI sequence (Firefox) URIError: String contained an illegal UTF-16 sequence. (Safari)\nError type\nURIError\nWhat went wrong?\nURI encoding or decoding wasn't successful. An argument given to either the\ndecodeURI\n, encodeURI\n, encodeURIComponent\n, or\ndecodeURIComponent\nfunction was not valid, so that the function was unable\nencode or decode properly.\nExamples\nEncoding\nEncoding replaces each instance of certain characters by one, two, three, or four\nescape sequences representing the UTF-8 encoding of the character. An\nURIError\nwill be thrown if there is an attempt to encode a surrogate which\nis not part of a high-low pair, for example:\nencodeURI(\"\\uD800\");\n// \"URIError: malformed URI sequence\"\nencodeURI(\"\\uDFFF\");\n// \"URIError: malformed URI sequence\"\nA high-low pair is OK. For example:\nencodeURI(\"\\uD800\\uDFFF\");\n// \"%F0%90%8F%BF\"\nDecoding\nDecoding 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:\ndecodeURIComponent(\"%E0%A4%A\");\n// \"URIError: malformed URI sequence\"\nWith proper input, this should usually look like something like this:\ndecodeURIComponent(\"JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B\");\n// \"JavaScript_\u0448\u0435\u043b\u043b\u044b\"", "code_snippets": ["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_\u0448\u0435\u043b\u043b\u044b\"\n"], "language": "JavaScript", "source": "mdn", "token_count": 440} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length", "title": "Function: length", "content": "Function: length\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe length\ndata property of a Function\ninstance indicates the number of parameters expected by the function.\nTry it\nfunction func1() {}\nfunction func2(a, b) {}\nconsole.log(func1.length);\n// Expected output: 0\nconsole.log(func2.length);\n// Expected output: 2\nValue\nA number.\nProperty attributes of Function: length | |\n|---|---|\n| Writable | no |\n| Enumerable | no |\n| Configurable | yes |\nDescription\nA Function\nobject's length\nproperty indicates how many arguments the function expects, i.e., the number of formal parameters:\n- Only parameters before the first one with a default value are counted.\n- A destructuring pattern counts as a single parameter.\n- The rest parameter is excluded.\nBy contrast, arguments.length\nis local to a function and provides the number of arguments actually passed to the function.\nThe Function\nconstructor is itself a Function\nobject. Its length\ndata property has a value of 1\n.\nDue to historical reasons, Function.prototype\nis a callable itself. The length\nproperty of Function.prototype\nhas a value of 0\n.\nExamples\nUsing function length\nconsole.log(Function.length); // 1\nconsole.log((() => {}).length); // 0\nconsole.log(((a) => {}).length); // 1\nconsole.log(((a, b) => {}).length); // 2 etc.\nconsole.log(((...args) => {}).length);\n// 0, rest parameter is not counted\nconsole.log(((a, b = 1, c) => {}).length);\n// 1, only parameters before the first one with\n// a default value are counted\nconsole.log((({ a, b }, [c, d]) => {}).length);\n// 2, destructuring patterns each count as\n// a single parameter\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-function-instances-length |", "code_snippets": ["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"], "language": "JavaScript", "source": "mdn", "token_count": 611} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_delete", "title": "TypeError: property \"x\" is non-configurable and can't be deleted", "content": "TypeError: property \"x\" is non-configurable and can't be deleted\nThe 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.\nMessage\nTypeError: Cannot delete property 'x' of # (V8-based) TypeError: property \"x\" is non-configurable and can't be deleted (Firefox) TypeError: Unable to delete property. (Safari)\nError type\nTypeError\nin strict mode only.\nWhat went wrong?\nIt was attempted to delete a property, but that property is non-configurable. The\nconfigurable\nattribute controls whether the property can be deleted from\nthe object and whether its attributes (other than writable\n) can be changed.\nThis error happens only in strict mode code. In\nnon-strict code, the operation returns false\n.\nExamples\nAttempting to delete non-configurable properties\nNon-configurable properties are not super common, but they can be created using\nObject.defineProperty()\nor Object.freeze()\n.\n\"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\nThere are also a few non-configurable properties built into JavaScript. Maybe you tried to delete a mathematical constant.\n\"use strict\";\ndelete Math.PI; // TypeError", "code_snippets": ["\"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"], "language": "JavaScript", "source": "mdn", "token_count": 461} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse", "title": "JSON.parse()", "content": "JSON.parse()\nBaseline\nWidely available\n*\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\n* Some parts of this feature may have varying levels of support.\nThe JSON.parse()\nstatic method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.\nTry it\nconst json = '{\"result\":true, \"count\":42}';\nconst obj = JSON.parse(json);\nconsole.log(obj.count);\n// Expected output: 42\nconsole.log(obj.result);\n// Expected output: true\nSyntax\nJSON.parse(text)\nJSON.parse(text, reviver)\nParameters\ntext\n-\nThe string to parse as JSON. See the\nJSON\nobject for a description of JSON syntax. reviver\nOptional-\nIf a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments:\nkey\n-\nThe key associated with the value.\nvalue\n-\nThe value produced by parsing.\ncontext\nOptional-\nA context object that holds state relevant to the current expression being revived. It is a new object for each invocation of the reviver function. It is only passed when reviving primitive values, but not when\nvalue\nis an object or array. It contains the following property:source\n-\nThe original JSON string representing this value.\nReturn value\nThe Object\n, Array\n, string, number, boolean, or null\nvalue corresponding to the given JSON text\n.\nExceptions\nSyntaxError\n-\nThrown if the string to parse is not valid JSON.\nDescription\nJSON.parse()\nparses a JSON string according to the JSON grammar, then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the \"__proto__\"\nkey \u2014 see Object literal syntax vs. JSON.\nThe reviver parameter\nIf a reviver\nis specified, the value computed by parsing is transformed before being returned. Specifically, the computed value and all its properties (in a depth-first fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver\n.\nThe reviver\nis called with the object containing the property being processed as this\n(unless you define the reviver\nas an arrow function, in which case there's no separate this\nbinding) and two arguments: key\nand value\n, representing the property name as a string (even for arrays) and the property value. For primitive values, an additional context\nparameter is passed, which contains the source text of this value. If the reviver\nfunction returns undefined\n(or returns no value \u2014 for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the reviver\nonly transforms some values and not others, be certain to return all untransformed values as-is \u2014 otherwise, they will be deleted from the resulting object.\nSimilar to the replacer\nparameter of JSON.stringify()\n, for arrays and objects, reviver\nwill be last called on the root value with an empty string as the key\nand the root object as the value\n. For other valid JSON values, reviver\nworks similarly and is called once with an empty string as the key\nand the value itself as the value\n.\nIf you return another value from reviver\n, that value will completely replace the originally parsed value. This even applies to the root value. For example:\nconst transformedObj = JSON.parse('[1,5,{\"s\":1}]', (key, value) =>\ntypeof value === \"object\" ? undefined : value,\n);\nconsole.log(transformedObj); // undefined\nThere is no way to work around this generically. You cannot specially handle the case where key\nis an empty string, because JSON objects can also contain keys that are empty strings. You need to know very precisely what kind of transformation is needed for each key when implementing the reviver.\nNote that reviver\nis run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. One way to transfer large numbers without loss of precision is to serialize them as strings, and revive them to BigInts, or other appropriate arbitrary precision formats.\nYou can also use the context.source\nproperty to access the original JSON source text representing the value, as shown below:\nconst bigJSON = '{\"gross_gdp\": 12345678901234567890}';\nconst bigObj = JSON.parse(bigJSON, (key, value, context) => {\nif (key === \"gross_gdp\") {\n// Ignore the value because it has already lost precision\nreturn BigInt(context.source);\n}\nreturn value;\n});\nExamples\nUsing JSON.parse()\nJSON.parse(\"{}\"); // {}\nJSON.parse(\"true\"); // true\nJSON.parse('\"foo\"'); // \"foo\"\nJSON.parse('[1, 5, \"false\"]'); // [1, 5, \"false\"]\nJSON.parse(\"null\"); // null\nUsing the reviver parameter\nJSON.parse(\n'{\"p\": 5}',\n(key, value) =>\ntypeof value === \"number\"\n? value * 2 // return value * 2 for numbers\n: value, // return everything else unchanged\n);\n// { p: 10 }\nJSON.parse('{\"1\": 1, \"2\": 2, \"3\": {\"4\": 4, \"5\": {\"6\": 6}}}', (key, value) => {\nconsole.log(key);\nreturn value;\n});\n// 1\n// 2\n// 4\n// 6\n// 5\n// 3\n// \"\"\nUsing reviver when paired with the replacer of JSON.stringify()\nIn order for a value to properly round-trip (that is, it gets deserialized to the same original object), the serialization process must preserve the type information. For example, you can use the replacer\nparameter of JSON.stringify()\nfor this purpose:\n// Maps are normally serialized as objects with no properties.\n// We can use the replacer to specify the entries to be serialized.\nconst map = new Map([\n[1, \"one\"],\n[2, \"two\"],\n[3, \"three\"],\n]);\nconst jsonText = JSON.stringify(map, (key, value) =>\nvalue instanceof Map ? Array.from(value.entries()) : value,\n);\nconsole.log(jsonText);\n// [[1,\"one\"],[2,\"two\"],[3,\"three\"]]\nconst map2 = JSON.parse(jsonText, (key, value) =>\nArray.isArray(value) && value.every(Array.isArray) ? new Map(value) : value,\n);\nconsole.log(map2);\n// Map { 1 => \"one\", 2 => \"two\", 3 => \"three\" }\nBecause JSON has no syntax space for annotating type metadata, in order to revive values that are not plain objects, you have to consider one of the following:\n- Serialize the entire object to a string and prefix it with a type tag.\n- \"Guess\" based on the structure of the data (for example, an array of two-member arrays)\n- If the shape of the payload is fixed, based on the property name (for example, all properties called\nregistry\nholdMap\nobjects).\nIllegal JSON\nWhen JSON.parse\nreceives a string that does not conform to the JSON grammar, it throws a SyntaxError\n.\nArrays and objects cannot have trailing commas in JSON:\nJSON.parse(\"[1, 2, 3, 4, ]\");\n// SyntaxError: Unexpected token ] in JSON at position 13\nJSON.parse('{\"foo\": 1, }');\n// SyntaxError: Unexpected token } in JSON at position 12\nJSON strings must be delimited by double (not single) quotes:\nJSON.parse(\"{'foo': 1}\");\n// SyntaxError: Unexpected token ' in JSON at position 1\nJSON.parse(\"'string'\");\n// SyntaxError: Unexpected token ' in JSON at position 0\nIf you are writing JSON inside a JavaScript string literal, you should either use single quotes to delimit the JavaScript string literal, or escape the double quotes that delimit the JSON string:\nJSON.parse('{\"foo\": 1}'); // OK\nJSON.parse(\"{\\\"foo\\\": 1}\"); // OK\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-json.parse |", "code_snippets": ["const json = '{\"result\":true, \"count\":42}';\nconst obj = JSON.parse(json);\n\nconsole.log(obj.count);\n// Expected output: 42\n\nconsole.log(obj.result);\n// Expected output: true\n", "JSON.parse(text)\nJSON.parse(text, reviver)\n", "const transformedObj = JSON.parse('[1,5,{\"s\":1}]', (key, value) =>\n typeof value === \"object\" ? undefined : value,\n);\n\nconsole.log(transformedObj); // undefined\n", "const bigJSON = '{\"gross_gdp\": 12345678901234567890}';\nconst bigObj = JSON.parse(bigJSON, (key, value, context) => {\n if (key === \"gross_gdp\") {\n // Ignore the value because it has already lost precision\n return BigInt(context.source);\n }\n return value;\n});\n", "JSON.parse(\"{}\"); // {}\nJSON.parse(\"true\"); // true\nJSON.parse('\"foo\"'); // \"foo\"\nJSON.parse('[1, 5, \"false\"]'); // [1, 5, \"false\"]\nJSON.parse(\"null\"); // null\n", "JSON.parse(\n '{\"p\": 5}',\n (key, value) =>\n typeof value === \"number\"\n ? value * 2 // return value * 2 for numbers\n : value, // return everything else unchanged\n);\n// { p: 10 }\n\nJSON.parse('{\"1\": 1, \"2\": 2, \"3\": {\"4\": 4, \"5\": {\"6\": 6}}}', (key, value) => {\n console.log(key);\n return value;\n});\n// 1\n// 2\n// 4\n// 6\n// 5\n// 3\n// \"\"\n", "// Maps are normally serialized as objects with no properties.\n// We can use the replacer to specify the entries to be serialized.\nconst map = new Map([\n [1, \"one\"],\n [2, \"two\"],\n [3, \"three\"],\n]);\n\nconst jsonText = JSON.stringify(map, (key, value) =>\n value instanceof Map ? Array.from(value.entries()) : value,\n);\n\nconsole.log(jsonText);\n// [[1,\"one\"],[2,\"two\"],[3,\"three\"]]\n\nconst map2 = JSON.parse(jsonText, (key, value) =>\n Array.isArray(value) && value.every(Array.isArray) ? new Map(value) : value,\n);\n\nconsole.log(map2);\n// Map { 1 => \"one\", 2 => \"two\", 3 => \"three\" }\n", "JSON.parse(\"[1, 2, 3, 4, ]\");\n// SyntaxError: Unexpected token ] in JSON at position 13\n\nJSON.parse('{\"foo\": 1, }');\n// SyntaxError: Unexpected token } in JSON at position 12\n", "JSON.parse(\"{'foo': 1}\");\n// SyntaxError: Unexpected token ' in JSON at position 1\n\nJSON.parse(\"'string'\");\n// SyntaxError: Unexpected token ' in JSON at position 0\n", "JSON.parse('{\"foo\": 1}'); // OK\nJSON.parse(\"{\\\"foo\\\": 1}\"); // OK\n"], "language": "JavaScript", "source": "mdn", "token_count": 2439} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/symbol/toprimitive/index.md\n\n# Original Wiki contributors\nmfuji09\nfscholz\nwbamberg\nDelapouite\njameshkramer\nGreenJello\nnmve\nKonrud\nkdex\nHugoGiraudel\nZeikJT\nThe-Quill\narai\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 74} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Now/zonedDateTimeISO", "title": "Temporal.Now.zonedDateTimeISO()", "content": "Temporal.Now.zonedDateTimeISO()\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe Temporal.Now.zonedDateTimeISO()\nstatic method returns the current date and time as a Temporal.ZonedDateTime\nobject, in the ISO 8601 calendar and the specified time zone.\nSyntax\nTemporal.Now.zonedDateTimeISO()\nTemporal.Now.zonedDateTimeISO(timeZone)\nParameters\ntimeZone\nOptional-\nEither a string or a\nTemporal.ZonedDateTime\ninstance representing the time zone to interpret the system time in. If aTemporal.ZonedDateTime\ninstance, 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).\nReturn value\nThe current date and time in the specified time zone, as a Temporal.ZonedDateTime\nobject using the ISO 8601 calendar. Has the same precision as Temporal.Now.instant()\n.\nExceptions\nRangeError\n-\nThrown if the time zone is invalid.\nExamples\nUsing Temporal.Now.zonedDateTimeISO()\n// The current date and time in the system's time zone\nconst dateTime = Temporal.Now.zonedDateTimeISO();\nconsole.log(dateTime); // e.g.: 2021-10-01T06:12:34.567890123+03:00[Africa/Nairobi]\n// The current date and time in the \"America/New_York\" time zone\nconst dateTimeInNewYork = Temporal.Now.zonedDateTimeISO(\"America/New_York\");\nconsole.log(dateTimeInNewYork); // e.g.: 2021-09-30T23:12:34.567890123-04:00[America/New_York]\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-temporal.now.zoneddatetimeiso |", "code_snippets": ["Temporal.Now.zonedDateTimeISO()\nTemporal.Now.zonedDateTimeISO(timeZone)\n", "// The current date and time in the system's time zone\nconst dateTime = Temporal.Now.zonedDateTimeISO();\nconsole.log(dateTime); // e.g.: 2021-10-01T06:12:34.567890123+03:00[Africa/Nairobi]\n\n// The current date and time in the \"America/New_York\" time zone\nconst dateTimeInNewYork = Temporal.Now.zonedDateTimeISO(\"America/New_York\");\nconsole.log(dateTimeInNewYork); // e.g.: 2021-09-30T23:12:34.567890123-04:00[America/New_York]\n"], "language": "JavaScript", "source": "mdn", "token_count": 527} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts", "title": "Intl.NumberFormat.prototype.formatToParts()", "content": "Intl.NumberFormat.prototype.formatToParts()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since September 2019.\nThe formatToParts()\nmethod of Intl.NumberFormat\ninstances returns an array of objects representing each part of the formatted string that would be returned by format()\n. It is useful for building custom strings from the locale-specific tokens.\nTry it\nconst amount = 654321.987;\nconst options = { style: \"currency\", currency: \"USD\" };\nconst numberFormat = new Intl.NumberFormat(\"en-US\", options);\nconst parts = numberFormat.formatToParts(amount);\nconst partValues = parts.map((p) => p.value);\nconsole.log(partValues);\n// Expected output: \"[\"$\", \"654\", \",\", \"321\", \".\", \"99\"]\"\nSyntax\nformatToParts(number)\nParameters\nnumber\n-\nA\nNumber\n,BigInt\n, or string, to format. Strings are parsed in the same way as in number conversion, except thatformatToParts()\nwill use the exact value that the string represents, avoiding loss of precision during implicitly conversion to a number.\nReturn value\nAn Array\nof objects containing the formatted number in parts. Each object has two properties, type\nand value\n, each containing a string. The string concatenation of value\n, in the order provided, will result in the same string as format()\n. The type\nmay be one of the following:\nliteral\n-\nAny string that's a part of the format pattern; for example\n\" \"\n. Note that common tokens like the decimal separator or the plus/minus signs have their own token types. integer\n-\nThe integral part of the number, or a segment of it if using grouping (controlled by\noptions.useGrouping\n). group\n-\nThe group separator string, such as\n\",\"\n. Only present when using grouping (controlled byoptions.useGrouping\n). decimal\n-\nThe decimal separator string, such as\n\".\"\n. Only present whenfraction\nis present. fraction\n-\nThe fractional part of the number.\ncompact\n-\nThe compact exponent, such as\n\"M\"\nor\"thousands\"\n. Only present whenoptions.notation\nis\"compact\"\n. The form (\"short\"\nor\"long\"\n) can be controlled viaoptions.compactDisplay\n. exponentSeparator\n-\nThe exponent separator, such as\n\"E\"\n. Only present whenoptions.notation\nis\"scientific\"\nor\"engineering\"\n. exponentMinusSign\n-\nThe exponent minus sign string, such as\n\"-\"\n. Only present whenoptions.notation\nis\"scientific\"\nor\"engineering\"\nand the exponent is negative. exponentInteger\n-\nThe exponent's integer value. Only present when\noptions.notation\nis\"scientific\"\nor\"engineering\"\n. nan\n-\nA string representing\nNaN\n, such as\"NaN\"\n. This is the sole token representing the number itself when the number isNaN\n. infinity\n-\nA string representing\nInfinity\nor-Infinity\n, such as\"\u221e\"\n. This is the sole token representing the number itself when the number isInfinity\nor-Infinity\n. plusSign\n-\nThe plus sign, such as\n\"+\"\n. minusSign\n-\nThe minus sign, such as\n\"-\"\n. percentSign\n-\nThe percent sign, such as\n\"%\"\n. Only present whenoptions.style\nis\"percent\"\n. unit\n-\nThe unit string, such as\n\"l\"\nor\"litres\"\n. Only present whenoptions.style\nis\"unit\"\n. The form (\"short\"\n,\"narrow\"\n, or\"long\"\n) can be controlled viaoptions.unitDisplay\n. currency\n-\nThe currency string, such as\n\"$\"\n,\"\u20ac\"\n,\"Dollar\"\n, or\"Euro\"\n. Only present whenoptions.style\nis\"currency\"\n. The form (\"code\"\n,\"symbol\"\n,\"narrowSymbol\"\n, or\"name\"\n) can be controlled viaoptions.currencyDisplay\n. unknown\n-\nReserved for any token that's not recognized as one of the above; should be rarely encountered.\nExamples\nUsing formatToParts()\nThe format()\nmethod outputs localized, opaque strings that cannot be manipulated directly:\nconst number = 3500;\nconst formatter = new Intl.NumberFormat(\"de-DE\", {\nstyle: \"currency\",\ncurrency: \"EUR\",\n});\nformatter.format(number);\n// \"3.500,00 \u20ac\"\nHowever, in many user interfaces you may want to customize the formatting of this string, or interleave it with other texts. The formatToParts()\nmethod produces the same information in parts:\nformatter.formatToParts(number);\n// return value:\n[\n{ type: \"integer\", value: \"3\" },\n{ type: \"group\", value: \".\" },\n{ type: \"integer\", value: \"500\" },\n{ type: \"decimal\", value: \",\" },\n{ type: \"fraction\", value: \"00\" },\n{ type: \"literal\", value: \" \" },\n{ type: \"currency\", value: \"\u20ac\" },\n];\nNow the information is available separately and it can be formatted and concatenated again in a customized way. For example by using Array.prototype.map()\n, arrow functions, a switch statement, template literals, and Array.prototype.join()\n, to insert additional markup for certain components.\nconst numberString = formatter\n.formatToParts(number)\n.map(({ type, value }) => {\nswitch (type) {\ncase \"currency\":\nreturn `${value}`;\ndefault:\nreturn value;\n}\n})\n.join(\"\");\nconsole.log(numberString);\n// \"3.500,00 \u20ac\"\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # sec-intl.numberformat.prototype.formattoparts |", "code_snippets": ["const amount = 654321.987;\nconst options = { style: \"currency\", currency: \"USD\" };\nconst numberFormat = new Intl.NumberFormat(\"en-US\", options);\n\nconst parts = numberFormat.formatToParts(amount);\nconst partValues = parts.map((p) => p.value);\n\nconsole.log(partValues);\n// Expected output: \"[\"$\", \"654\", \",\", \"321\", \".\", \"99\"]\"\n", "formatToParts(number)\n", "const number = 3500;\n\nconst formatter = new Intl.NumberFormat(\"de-DE\", {\n style: \"currency\",\n currency: \"EUR\",\n});\n\nformatter.format(number);\n// \"3.500,00 \u20ac\"\n", "formatter.formatToParts(number);\n\n// return value:\n[\n { type: \"integer\", value: \"3\" },\n { type: \"group\", value: \".\" },\n { type: \"integer\", value: \"500\" },\n { type: \"decimal\", value: \",\" },\n { type: \"fraction\", value: \"00\" },\n { type: \"literal\", value: \" \" },\n { type: \"currency\", value: \"\u20ac\" },\n];\n", "const numberString = formatter\n .formatToParts(number)\n .map(({ type, value }) => {\n switch (type) {\n case \"currency\":\n return `${value}`;\n default:\n return value;\n }\n })\n .join(\"\");\n\nconsole.log(numberString);\n// \"3.500,00 \u20ac\"\n"], "language": "JavaScript", "source": "mdn", "token_count": 1509} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Now/timeZoneId/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/temporal/now/timezoneid/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 40} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat/datetimeformat/index.md\n\n# Original Wiki contributors\nmfuji09\nhamishwillee\nLouis-Aime\njshado1\nfscholz\ndanielmayorga\nsideshowbarker\nwbamberg\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 72} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/displayName", "title": "Function: displayName", "content": "Function: displayName\nNon-standard: This feature is not standardized. We do not recommend using non-standard features in production, as they have limited browser support, and may change or be removed. However, they can be a suitable alternative in specific cases where no standard option exists.\nThe optional displayName\nproperty of a Function\ninstance specifies the display name of the function.\nValue\nThe displayName\nproperty is not initially present on any function \u2014 it's added by the code authors. For the purpose of display, it should be a string.\nDescription\nThe displayName\nproperty, if present, may be preferred by consoles and profilers over the name\nproperty to be displayed as the name of a function.\nAmong browsers, only the Firefox console utilizes this property. React devtools also use the displayName\nproperty when displaying the component tree.\nFirefox does some basic attempts to decode the displayName\nthat's possibly generated by the anonymous JavaScript functions naming convention algorithm. The following patterns are detected:\n- If\ndisplayName\nends with a sequence of alphanumeric characters,_\n, and$\n, the longest such suffix is displayed. - If\ndisplayName\nends with a sequence of[]\n-enclosed characters, that sequence is displayed without the square brackets. - If\ndisplayName\nends with a sequence of alphanumeric characters and_\nfollowed by some/\n,.\n, or<\n, the sequence is returned without the trailing/\n,.\n, or<\ncharacters. - If\ndisplayName\nends with a sequence of alphanumeric characters and_\nfollowed by(^)\n, the sequence is displayed without the(^)\n.\nIf none of the above patterns match, the entire displayName\nis displayed.\nExamples\nSetting a displayName\nBy entering the following in a Firefox console, it should display as something like function MyFunction()\n:\nfunction a() {}\na.displayName = \"MyFunction\";\na; // function MyFunction()\nChanging displayName dynamically\nYou can dynamically change the displayName\nof a function:\nconst object = {\n// anonymous\nsomeMethod: function someMethod(value) {\nsomeMethod.displayName = `someMethod (${value})`;\n},\n};\nconsole.log(object.someMethod.displayName); // undefined\nobject.someMethod(\"123\");\nconsole.log(object.someMethod.displayName); // \"someMethod (123)\"\nCleaning of displayName\nFirefox devtools would clean up a few common patterns in the displayName\nproperty before displaying it.\nfunction foo() {}\nfunction testName(name) {\nfoo.displayName = name;\nconsole.log(foo);\n}\ntestName(\"$foo$\"); // function $foo$()\ntestName(\"foo bar\"); // function bar()\ntestName(\"Foo.prototype.add\"); // function add()\ntestName(\"foo .\"); // function foo .()\ntestName(\"foo <\"); // function foo <()\ntestName(\"foo?\"); // function foo?()\ntestName(\"foo()\"); // function foo()()\ntestName(\"[...]\"); // function ...()\ntestName(\"foo<\"); // function foo()\ntestName(\"foo...\"); // function foo()\ntestName(\"foo(^)\"); // function foo()\nSpecifications\nNot part of any standard.", "code_snippets": ["function a() {}\na.displayName = \"MyFunction\";\n\na; // function MyFunction()\n", "const object = {\n // anonymous\n someMethod: function someMethod(value) {\n someMethod.displayName = `someMethod (${value})`;\n },\n};\n\nconsole.log(object.someMethod.displayName); // undefined\n\nobject.someMethod(\"123\");\nconsole.log(object.someMethod.displayName); // \"someMethod (123)\"\n", "function foo() {}\n\nfunction testName(name) {\n foo.displayName = name;\n console.log(foo);\n}\n\ntestName(\"$foo$\"); // function $foo$()\ntestName(\"foo bar\"); // function bar()\ntestName(\"Foo.prototype.add\"); // function add()\ntestName(\"foo .\"); // function foo .()\ntestName(\"foo <\"); // function foo <()\ntestName(\"foo?\"); // function foo?()\ntestName(\"foo()\"); // function foo()()\n\ntestName(\"[...]\"); // function ...()\ntestName(\"foo<\"); // function foo()\ntestName(\"foo...\"); // function foo()\ntestName(\"foo(^)\"); // function foo()\n"], "language": "JavaScript", "source": "mdn", "token_count": 953} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Symbol.unscopables/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/array/symbol.unscopables/index.md\n\n# Original Wiki contributors\nmfuji09\nwbamberg\nfscholz\nRainSlide\nnmve\nkdex\nmatt-tingen\nevilpie\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 64} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/resolvedOptions/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/listformat/resolvedoptions/index.md\n\n# Original Wiki contributors\nwbamberg\nfscholz\nSphinxKnight\nrwe2020\nsideshowbarker\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 63} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN", "title": "Number.NaN", "content": "Number.NaN\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe Number.NaN\nstatic data property represents Not-A-Number, which is equivalent to NaN\n. For more information about the behaviors of NaN\n, see the description for the global property.\nTry it\nfunction clean(x) {\nif (x === Number.NaN) {\n// Can never be true\nreturn null;\n}\nif (isNaN(x)) {\nreturn 0;\n}\n}\nconsole.log(clean(Number.NaN));\n// Expected output: 0\nValue\nThe number value NaN\n.\nProperty attributes of Number.NaN | |\n|---|---|\n| Writable | no |\n| Enumerable | no |\n| Configurable | no |\nDescription\nBecause NaN\nis a static property of Number\n, you always use it as Number.NaN\n, rather than as a property of a number value.\nExamples\nChecking whether values are numeric\njs\nfunction sanitize(x) {\nif (isNaN(x)) {\nreturn Number.NaN;\n}\nreturn x;\n}\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-number.nan |", "code_snippets": ["function clean(x) {\n if (x === Number.NaN) {\n // Can never be true\n return null;\n }\n if (isNaN(x)) {\n return 0;\n }\n}\n\nconsole.log(clean(Number.NaN));\n// Expected output: 0\n", "function sanitize(x) {\n if (isNaN(x)) {\n return Number.NaN;\n }\n return x;\n}\n"], "language": "JavaScript", "source": "mdn", "token_count": 322} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/format", "title": "Intl.ListFormat.prototype.format()", "content": "Intl.ListFormat.prototype.format()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since April 2021.\nThe format()\nmethod of Intl.ListFormat\ninstances returns a string with a\nlanguage-specific representation of the list.\nTry it\nconst vehicles = [\"Motorcycle\", \"Bus\", \"Car\"];\nconst formatter = new Intl.ListFormat(\"en\", {\nstyle: \"long\",\ntype: \"conjunction\",\n});\nconsole.log(formatter.format(vehicles));\n// Expected output: \"Motorcycle, Bus, and Car\"\nconst formatter2 = new Intl.ListFormat(\"de\", {\nstyle: \"short\",\ntype: \"disjunction\",\n});\nconsole.log(formatter2.format(vehicles));\n// Expected output: \"Motorcycle, Bus oder Car\"\nconst formatter3 = new Intl.ListFormat(\"en\", { style: \"narrow\", type: \"unit\" });\nconsole.log(formatter3.format(vehicles));\n// Expected output: \"Motorcycle Bus Car\"\nSyntax\nformat(list)\nParameters\nlist\n-\nAn 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.\nReturn value\nA language-specific formatted string representing the elements of the list.\nNote:\nMost of the time, the formatting returned by format()\nis consistent. However, the output may vary between implementations, even within the same locale \u2014 output variations are by design and allowed by the specification. It may also not be what you expect. For example, the string may use non-breaking spaces or be surrounded by bidirectional control characters. You should not compare the results of format()\nto hardcoded constants.\nExamples\nUsing format\nThe following example shows how to create a List formatter using the English language.\nconst list = [\"Motorcycle\", \"Bus\", \"Car\"];\nconsole.log(\nnew Intl.ListFormat(\"en-GB\", { style: \"long\", type: \"conjunction\" }).format(\nlist,\n),\n);\n// Motorcycle, Bus and Car\nconsole.log(\nnew Intl.ListFormat(\"en-GB\", { style: \"short\", type: \"disjunction\" }).format(\nlist,\n),\n);\n// Motorcycle, Bus or Car\nconsole.log(\nnew Intl.ListFormat(\"en-GB\", { style: \"narrow\", type: \"unit\" }).format(list),\n);\n// Motorcycle Bus Car\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # sec-Intl.ListFormat.prototype.format |", "code_snippets": ["const vehicles = [\"Motorcycle\", \"Bus\", \"Car\"];\n\nconst formatter = new Intl.ListFormat(\"en\", {\n style: \"long\",\n type: \"conjunction\",\n});\nconsole.log(formatter.format(vehicles));\n// Expected output: \"Motorcycle, Bus, and Car\"\n\nconst formatter2 = new Intl.ListFormat(\"de\", {\n style: \"short\",\n type: \"disjunction\",\n});\nconsole.log(formatter2.format(vehicles));\n// Expected output: \"Motorcycle, Bus oder Car\"\n\nconst formatter3 = new Intl.ListFormat(\"en\", { style: \"narrow\", type: \"unit\" });\nconsole.log(formatter3.format(vehicles));\n// Expected output: \"Motorcycle Bus Car\"\n", "format(list)\n", "const list = [\"Motorcycle\", \"Bus\", \"Car\"];\n\nconsole.log(\n new Intl.ListFormat(\"en-GB\", { style: \"long\", type: \"conjunction\" }).format(\n list,\n ),\n);\n// Motorcycle, Bus and Car\n\nconsole.log(\n new Intl.ListFormat(\"en-GB\", { style: \"short\", type: \"disjunction\" }).format(\n list,\n ),\n);\n// Motorcycle, Bus or Car\n\nconsole.log(\n new Intl.ListFormat(\"en-GB\", { style: \"narrow\", type: \"unit\" }).format(list),\n);\n// Motorcycle Bus Car\n"], "language": "JavaScript", "source": "mdn", "token_count": 834} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only", "title": "TypeError: setting getter-only property \"x\"", "content": "TypeError: setting getter-only property \"x\"\nThe JavaScript strict mode-only exception \"setting getter-only property\" occurs when there is an attempt to set a new value to a property for which only a getter is specified, or when setting a private accessor property that similarly only has a getter defined.\nMessage\nTypeError: Cannot set property x of # which has only a getter (V8-based) TypeError: '#x' was defined without a setter (V8-based) TypeError: setting getter-only property \"x\" (Firefox) TypeError: Attempted to assign to readonly property. (Safari) TypeError: Trying to access an undefined private setter (Safari)\nError type\nTypeError\nin strict mode only.\nWhat went wrong?\nThere is an attempt to set a new value to a property for which only a getter is specified.\nWhile this will be silently ignored in non-strict mode, it will throw a\nTypeError\nin strict mode. Classes are always in strict mode, so assigning to a getter-only private element always throws this error.\nExamples\nProperty with no setter\nThe example below shows how to set a getter for a property.\nIt doesn't specify a setter, so a\nTypeError\nwill be thrown upon trying to set the temperature\nproperty to 30\n. For more details see also the\nObject.defineProperty()\npage.\n\"use strict\";\nfunction Archiver() {\nconst temperature = null;\nObject.defineProperty(this, \"temperature\", {\nget() {\nconsole.log(\"get!\");\nreturn temperature;\n},\n});\n}\nconst arc = new Archiver();\narc.temperature; // 'get!'\narc.temperature = 30;\n// TypeError: setting getter-only property \"temperature\"\nTo fix this error, you will either need to remove the arc.temperature = 30\nline, which attempts to\nset the temperature property, or you will need to implement a setter for it, for\nexample like this:\n\"use strict\";\nfunction Archiver() {\nlet temperature = null;\nconst archive = [];\nObject.defineProperty(this, \"temperature\", {\nget() {\nconsole.log(\"get!\");\nreturn temperature;\n},\nset(value) {\ntemperature = value;\narchive.push({ val: temperature });\n},\n});\nthis.getArchive = function () {\nreturn archive;\n};\n}\nconst arc = new Archiver();\narc.temperature; // 'get!'\narc.temperature = 11;\narc.temperature = 13;\narc.getArchive(); // [{ val: 11 }, { val: 13 }]", "code_snippets": ["\"use strict\";\n\nfunction Archiver() {\n const temperature = null;\n Object.defineProperty(this, \"temperature\", {\n get() {\n console.log(\"get!\");\n return temperature;\n },\n });\n}\n\nconst arc = new Archiver();\narc.temperature; // 'get!'\n\narc.temperature = 30;\n// TypeError: setting getter-only property \"temperature\"\n", "\"use strict\";\n\nfunction Archiver() {\n let temperature = null;\n const archive = [];\n\n Object.defineProperty(this, \"temperature\", {\n get() {\n console.log(\"get!\");\n return temperature;\n },\n set(value) {\n temperature = value;\n archive.push({ val: temperature });\n },\n });\n\n this.getArchive = function () {\n return archive;\n };\n}\n\nconst arc = new Archiver();\narc.temperature; // 'get!'\narc.temperature = 11;\narc.temperature = 13;\narc.getArchive(); // [{ val: 11 }, { val: 13 }]\n"], "language": "JavaScript", "source": "mdn", "token_count": 761} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatRange", "title": "Intl.NumberFormat.prototype.formatRange()", "content": "Intl.NumberFormat.prototype.formatRange()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since August 2023.\nThe formatRange()\nmethod of Intl.NumberFormat\ninstances formats a range of numbers according to the locale and formatting options of this Intl.NumberFormat\nobject.\nSyntax\nformatRange(startRange, endRange)\nParameters\nstartRange\n-\nA\nNumber\n,BigInt\n, or string, to format. Strings are parsed in the same way as in number conversion, except thatformatRange()\nwill use the exact value that the string represents, avoiding loss of precision during implicitly conversion to a number. endRange\nReturn value\nA string representing the given range of numbers formatted according to the locale and formatting options of this Intl.NumberFormat\nobject. If the start and end values are formatted to the same string, the output will only contain a single value, possibly prefixed with an \"approximately equals\" symbol (e.g., \"~$3\"). The insertion of this symbol only depends on the locale settings, and is inserted even when startRange === endRange\n.\nExceptions\nRangeError\n-\nThrown if either\nstartRange\norendRange\nisNaN\nor an inconvertible string. TypeError\n-\nThrown if either\nstartRange\norendRange\nis undefined.\nDescription\nThe formatRange\ngetter function formats a range of numbers into a string according to the locale and formatting options of this Intl.NumberFormat\nobject from which it is called.\nExamples\nUsing formatRange\nUse the formatRange\ngetter function for formatting a range of currency values:\nconst nf = new Intl.NumberFormat(\"en-US\", {\nstyle: \"currency\",\ncurrency: \"USD\",\nmaximumFractionDigits: 0,\n});\nconsole.log(nf.formatRange(3, 5)); // \"$3 \u2013 $5\"\n// Note: the \"approximately equals\" symbol is added if\n// startRange and endRange round to the same values.\nconsole.log(nf.formatRange(2.9, 3.1)); // \"~$3\"\nconst nf = new Intl.NumberFormat(\"es-ES\", {\nstyle: \"currency\",\ncurrency: \"EUR\",\nmaximumFractionDigits: 0,\n});\nconsole.log(nf.formatRange(3, 5)); // \"3-5 \u20ac\"\nconsole.log(nf.formatRange(2.9, 3.1)); // \"~3 \u20ac\"\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # sec-intl.numberformat.prototype.formatrange |", "code_snippets": ["formatRange(startRange, endRange)\n", "const nf = new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n maximumFractionDigits: 0,\n});\n\nconsole.log(nf.formatRange(3, 5)); // \"$3 \u2013 $5\"\n\n// Note: the \"approximately equals\" symbol is added if\n// startRange and endRange round to the same values.\nconsole.log(nf.formatRange(2.9, 3.1)); // \"~$3\"\n", "const nf = new Intl.NumberFormat(\"es-ES\", {\n style: \"currency\",\n currency: \"EUR\",\n maximumFractionDigits: 0,\n});\n\nconsole.log(nf.formatRange(3, 5)); // \"3-5 \u20ac\"\nconsole.log(nf.formatRange(2.9, 3.1)); // \"~3 \u20ac\"\n"], "language": "JavaScript", "source": "mdn", "token_count": 708} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter", "title": "Intl.Segmenter", "content": "Intl.Segmenter\nBaseline\n2024\nNewly available\nSince April 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.\nThe Intl.Segmenter\nobject enables locale-sensitive text segmentation, enabling you to get meaningful items (graphemes, words or sentences) from a string.\nTry it\nconst segmenterFr = new Intl.Segmenter(\"fr\", { granularity: \"word\" });\nconst string = \"Que ma joie demeure\";\nconst iterator = segmenterFr.segment(string)[Symbol.iterator]();\nconsole.log(iterator.next().value.segment);\n// Expected output: 'Que'\nconsole.log(iterator.next().value.segment);\n// Expected output: ' '\nConstructor\nIntl.Segmenter()\n-\nCreates a new\nIntl.Segmenter\nobject.\nStatic methods\nIntl.Segmenter.supportedLocalesOf()\n-\nReturns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.\nInstance properties\nThese properties are defined on Intl.Segmenter.prototype\nand shared by all Intl.Segmenter\ninstances.\nIntl.Segmenter.prototype.constructor\n-\nThe constructor function that created the instance object. For\nIntl.Segmenter\ninstances, the initial value is theIntl.Segmenter\nconstructor. Intl.Segmenter.prototype[Symbol.toStringTag]\n-\nThe initial value of the\n[Symbol.toStringTag]\nproperty is the string\"Intl.Segmenter\"\n. This property is used inObject.prototype.toString()\n.\nInstance methods\nIntl.Segmenter.prototype.resolvedOptions()\n-\nReturns a new object with properties reflecting the locale and granularity options computed during initialization of this\nIntl.Segmenter\nobject. Intl.Segmenter.prototype.segment()\n-\nReturns a new iterable\nSegments\ninstance representing the segments of a string according to the locale and granularity of thisIntl.Segmenter\ninstance.\nExamples\nBasic usage and difference from String.prototype.split()\nIf we were to use String.prototype.split(\" \")\nto segment a text in words, we would not get the correct result if the locale of the text does not use whitespaces between words (which is the case for Japanese, Chinese, Thai, Lao, Khmer, Myanmar, etc.).\nconst str = \"\u543e\u8f29\u306f\u732b\u3067\u3042\u308b\u3002\u540d\u524d\u306f\u305f\u306c\u304d\u3002\";\nconsole.table(str.split(\" \"));\n// ['\u543e\u8f29\u306f\u732b\u3067\u3042\u308b\u3002\u540d\u524d\u306f\u305f\u306c\u304d\u3002']\n// The two sentences are not correctly segmented.\nconst str = \"\u543e\u8f29\u306f\u732b\u3067\u3042\u308b\u3002\u540d\u524d\u306f\u305f\u306c\u304d\u3002\";\nconst segmenterJa = new Intl.Segmenter(\"ja-JP\", { granularity: \"word\" });\nconst segments = segmenterJa.segment(str);\nconsole.table(Array.from(segments));\n// [{segment: '\u543e\u8f29', index: 0, input: '\u543e\u8f29\u306f\u732b\u3067\u3042\u308b\u3002\u540d\u524d\u306f\u305f\u306c\u304d\u3002', isWordLike: true},\n// etc.\n// ]\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # segmenter-objects |", "code_snippets": ["const segmenterFr = new Intl.Segmenter(\"fr\", { granularity: \"word\" });\nconst string = \"Que ma joie demeure\";\n\nconst iterator = segmenterFr.segment(string)[Symbol.iterator]();\n\nconsole.log(iterator.next().value.segment);\n// Expected output: 'Que'\n\nconsole.log(iterator.next().value.segment);\n// Expected output: ' '\n", "const str = \"\u543e\u8f29\u306f\u732b\u3067\u3042\u308b\u3002\u540d\u524d\u306f\u305f\u306c\u304d\u3002\";\nconsole.table(str.split(\" \"));\n// ['\u543e\u8f29\u306f\u732b\u3067\u3042\u308b\u3002\u540d\u524d\u306f\u305f\u306c\u304d\u3002']\n// The two sentences are not correctly segmented.\n", "const str = \"\u543e\u8f29\u306f\u732b\u3067\u3042\u308b\u3002\u540d\u524d\u306f\u305f\u306c\u304d\u3002\";\nconst segmenterJa = new Intl.Segmenter(\"ja-JP\", { granularity: \"word\" });\n\nconst segments = segmenterJa.segment(str);\nconsole.table(Array.from(segments));\n// [{segment: '\u543e\u8f29', index: 0, input: '\u543e\u8f29\u306f\u732b\u3067\u3042\u308b\u3002\u540d\u524d\u306f\u305f\u306c\u304d\u3002', isWordLike: true},\n// etc.\n// ]\n"], "language": "JavaScript", "source": "mdn", "token_count": 842} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules", "title": "Intl.PluralRules", "content": "Intl.PluralRules\nBaseline\nWidely available\n*\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since September 2019.\n* Some parts of this feature may have varying levels of support.\nThe Intl.PluralRules\nobject enables plural-sensitive formatting and plural-related language rules.\nDescription\nLanguages use different patterns for expressing both plural numbers of items (cardinal numbers) and for expressing the order of items (ordinal numbers). English has two forms for expressing cardinal numbers: one for the singular \"item\" (1 hour, 1 dog, 1 fish) and the other for zero or any other number of \"items\" (0 hours, 2 lemmings, 100000.5 fish), while Chinese has only one form, and Arabic has six! Similarly, English has four forms for expressing ordinal numbers: \"th\", \"st\", \"nd\", \"rd\", giving the sequence: 0th, 1st, 2nd, 3rd, 4th, 5th, ..., 21st, 22nd, 23rd, 24th, 25th, and so on, while both Chinese and Arabic only have one form for ordinal numbers.\nGiven a particular language and set of formatting options, the methods Intl.PluralRules.prototype.select()\nand Intl.PluralRules.prototype.selectRange()\nreturn a tag that represents the plural form of a single or a range of numbers, cardinal or ordinal.\nCode can use the returned tags to represent numbers appropriately for the given language.\nThe full set of tags that might be returned are: zero\n, one\n, two\n, few\n, many\n, and other\n(the \"general\" plural form, also used if the language only has one form).\nAs English only has two forms for cardinal numbers, the select()\nmethod returns only two tags: \"one\"\nfor the singular case, and \"other\"\nfor all other cardinal numbers.\nThis allows construction of sentences that make sense in English for each case, such as: \"1 dog is happy; do you want to play with it?\" and \"10 dogs are happy; do you want to play with them?\".\nCreating appropriate sentences for each form depends on the language, and even in English may not be as simple as just adding \"s\" to a noun to make the plural form. Using the example above, we see that the form may affect:\n- Nouns: 1 dog, 2 dogs (but not \"fish\" or \"sheep\", which have the same singular and plural form).\n- Verbs: 1 dog is happy, 2 dogs are happy.\n- Pronouns (and other referents): Do you want to play with it / them.\nOther languages have more forms, and choosing appropriate sentences can be even more complex.\nselect()\ncan return any of four tags for ordinal numbers in English, representing each of the allowed forms: one\nfor \"st\" numbers (1, 21, 31, ...), two\nfor \"nd\" numbers (2, 22, 32, ...), few\nfor \"rd\" numbers (3, 33, 43, ...), and other\nfor \"th\" numbers (0, 4-20, etc.).\nAgain, the returned tags allow appropriate formatting of strings describing an ordinal number.\nFor more information about the rules and how they are used, see Plural Rules. For a list of the rules and how they apply for different languages, see the LDML Language Plural Rules.\nConstructor\nIntl.PluralRules()\n-\nCreates a new\nIntl.PluralRules\nobject.\nStatic methods\nIntl.PluralRules.supportedLocalesOf()\n-\nReturns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.\nInstance properties\nThese properties are defined on Intl.PluralRules.prototype\nand shared by all Intl.PluralRules\ninstances.\nIntl.PluralRules.prototype.constructor\n-\nThe constructor function that created the instance object. For\nIntl.PluralRules\ninstances, the initial value is theIntl.PluralRules\nconstructor. Intl.PluralRules.prototype[Symbol.toStringTag]\n-\nThe initial value of the\n[Symbol.toStringTag]\nproperty is the string\"Intl.PluralRules\"\n. This property is used inObject.prototype.toString()\n.\nInstance methods\nIntl.PluralRules.prototype.resolvedOptions()\n-\nReturns a new object with properties reflecting the locale and collation options computed during initialization of the object.\nIntl.PluralRules.prototype.select()\n-\nReturns a string indicating which plural rule to use for locale-aware formatting.\nIntl.PluralRules.prototype.selectRange()\n-\nThis method receives two values and returns a string indicating which plural rule to use for locale-aware formatting.\nExamples\nUsing locales\nThis example shows some of the variations in localized plural rules for cardinal numbers.\nIn order to get the format for the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the constructor locales\nargument:\n// US English\nconst enCardinalRules = new Intl.PluralRules(\"en-US\");\nconsole.log(enCardinalRules.select(0)); // \"other\"\nconsole.log(enCardinalRules.select(1)); // \"one\"\nconsole.log(enCardinalRules.select(2)); // \"other\"\nconsole.log(enCardinalRules.select(3)); // \"other\"\n// Arabic\nconst arCardinalRules = new Intl.PluralRules(\"ar-EG\");\nconsole.log(arCardinalRules.select(0)); // \"zero\"\nconsole.log(arCardinalRules.select(1)); // \"one\"\nconsole.log(arCardinalRules.select(2)); // \"two\"\nconsole.log(arCardinalRules.select(6)); // \"few\"\nconsole.log(arCardinalRules.select(18)); // \"many\"\nUsing options\nThe plural form of the specified number may also depend on constructor options\n, such as how the number is rounded, and whether it is cardinal or ordinal.\nThis example shows how you can set the type of rules to \"ordinal\", and how this affects the form for some numbers in US English.\n// US English - ordinal\nconst enOrdinalRules = new Intl.PluralRules(\"en-US\", { type: \"ordinal\" });\nconsole.log(enOrdinalRules.select(0)); // \"other\" (0th)\nconsole.log(enOrdinalRules.select(1)); // \"one\" (1st)\nconsole.log(enOrdinalRules.select(2)); // \"two\" (2nd)\nconsole.log(enOrdinalRules.select(3)); // \"few\" (3rd)\nconsole.log(enOrdinalRules.select(4)); // \"other\" (4th)\nconsole.log(enOrdinalRules.select(21)); // \"one\" (21st)\nFormatting text using the returned tag\nThe code below extends the previous example, showing how you might use the returned tag for an ordinal number to format text in English.\nconst enOrdinalRules = new Intl.PluralRules(\"en-US\", { type: \"ordinal\" });\nconst suffixes = new Map([\n[\"one\", \"st\"],\n[\"two\", \"nd\"],\n[\"few\", \"rd\"],\n[\"other\", \"th\"],\n]);\nconst formatOrdinals = (n) => {\nconst rule = enOrdinalRules.select(n);\nconst suffix = suffixes.get(rule);\nreturn `${n}${suffix}`;\n};\nformatOrdinals(0); // '0th'\nformatOrdinals(1); // '1st'\nformatOrdinals(2); // '2nd'\nformatOrdinals(3); // '3rd'\nformatOrdinals(4); // '4th'\nformatOrdinals(11); // '11th'\nformatOrdinals(21); // '21st'\nformatOrdinals(42); // '42nd'\nformatOrdinals(103); // '103rd'\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # pluralrules-objects |", "code_snippets": ["// US English\nconst enCardinalRules = new Intl.PluralRules(\"en-US\");\nconsole.log(enCardinalRules.select(0)); // \"other\"\nconsole.log(enCardinalRules.select(1)); // \"one\"\nconsole.log(enCardinalRules.select(2)); // \"other\"\nconsole.log(enCardinalRules.select(3)); // \"other\"\n\n// Arabic\nconst arCardinalRules = new Intl.PluralRules(\"ar-EG\");\nconsole.log(arCardinalRules.select(0)); // \"zero\"\nconsole.log(arCardinalRules.select(1)); // \"one\"\nconsole.log(arCardinalRules.select(2)); // \"two\"\nconsole.log(arCardinalRules.select(6)); // \"few\"\nconsole.log(arCardinalRules.select(18)); // \"many\"\n", "// US English - ordinal\nconst enOrdinalRules = new Intl.PluralRules(\"en-US\", { type: \"ordinal\" });\nconsole.log(enOrdinalRules.select(0)); // \"other\" (0th)\nconsole.log(enOrdinalRules.select(1)); // \"one\" (1st)\nconsole.log(enOrdinalRules.select(2)); // \"two\" (2nd)\nconsole.log(enOrdinalRules.select(3)); // \"few\" (3rd)\nconsole.log(enOrdinalRules.select(4)); // \"other\" (4th)\nconsole.log(enOrdinalRules.select(21)); // \"one\" (21st)\n", "const enOrdinalRules = new Intl.PluralRules(\"en-US\", { type: \"ordinal\" });\n\nconst suffixes = new Map([\n [\"one\", \"st\"],\n [\"two\", \"nd\"],\n [\"few\", \"rd\"],\n [\"other\", \"th\"],\n]);\nconst formatOrdinals = (n) => {\n const rule = enOrdinalRules.select(n);\n const suffix = suffixes.get(rule);\n return `${n}${suffix}`;\n};\n\nformatOrdinals(0); // '0th'\nformatOrdinals(1); // '1st'\nformatOrdinals(2); // '2nd'\nformatOrdinals(3); // '3rd'\nformatOrdinals(4); // '4th'\nformatOrdinals(11); // '11th'\nformatOrdinals(21); // '21st'\nformatOrdinals(42); // '42nd'\nformatOrdinals(103); // '103rd'\n"], "language": "JavaScript", "source": "mdn", "token_count": 2074} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/durationformat/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 39} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/errors/getter_only/index.md\n\n# Original Wiki contributors\nfscholz\nPatrickKettner\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 48} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing", "title": "Nullish coalescing operator (??)", "content": "Nullish coalescing operator (??)\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2020.\nThe nullish coalescing (??\n) operator is a logical\noperator that returns its right-hand side operand when its left-hand side operand is\nnull\nor undefined\n, and otherwise returns its left-hand side\noperand.\nTry it\nconst foo = null ?? \"default string\";\nconsole.log(foo);\n// Expected output: \"default string\"\nconst baz = 0 ?? 42;\nconsole.log(baz);\n// Expected output: 0\nSyntax\nleftExpr ?? rightExpr\nDescription\nThe nullish coalescing operator can be seen as a special case of the logical OR (||\n) operator. The latter returns the right-hand side operand if the left operand is any falsy value, not only null\nor undefined\n. In other words, if you use ||\nto provide some default value to another variable foo\n, you may encounter unexpected behaviors if you consider some falsy values as usable (e.g., ''\nor 0\n). See below for more examples.\nThe nullish coalescing operator has the fifth-lowest operator precedence, directly lower than ||\nand directly higher than the conditional (ternary) operator.\nIt is not possible to combine either the AND (&&\n) or OR operators (||\n) directly with ??\n. A syntax error will be thrown in such cases.\nnull || undefined ?? \"foo\"; // raises a SyntaxError\ntrue && undefined ?? \"foo\"; // raises a SyntaxError\nInstead, provide parenthesis to explicitly indicate precedence:\n(null || undefined) ?? \"foo\"; // returns \"foo\"\nExamples\nUsing the nullish coalescing operator\nIn this example, we will provide default values but keep values other than null\nor undefined\n.\nconst nullValue = null;\nconst emptyText = \"\"; // falsy\nconst someNumber = 42;\nconst valA = nullValue ?? \"default for A\";\nconst valB = emptyText ?? \"default for B\";\nconst valC = someNumber ?? 0;\nconsole.log(valA); // \"default for A\"\nconsole.log(valB); // \"\" (as the empty string is not null or undefined)\nconsole.log(valC); // 42\nAssigning a default value to a variable\nEarlier, when one wanted to assign a default value to a variable, a common pattern was to use the logical OR operator (||\n):\nlet foo;\n// foo is never assigned any value so it is still undefined\nconst someDummyText = foo || \"Hello!\";\nHowever, due to ||\nbeing a boolean logical operator, the left-hand-side operand was coerced to a boolean for the evaluation and any falsy value (including 0\n, ''\n, NaN\n, false\n, etc.) was not returned. This behavior may cause unexpected consequences if you consider 0\n, ''\n, or NaN\nas valid values.\nconst count = 0;\nconst text = \"\";\nconst qty = count || 42;\nconst message = text || \"hi!\";\nconsole.log(qty); // 42 and not 0\nconsole.log(message); // \"hi!\" and not \"\"\nThe nullish coalescing operator avoids this pitfall by only returning the second operand when the first one evaluates to either null\nor undefined\n(but no other falsy values):\nconst myText = \"\"; // An empty string (which is also a falsy value)\nconst notFalsyText = myText || \"Hello world\";\nconsole.log(notFalsyText); // Hello world\nconst preservingFalsy = myText ?? \"Hi neighborhood\";\nconsole.log(preservingFalsy); // '' (as myText is neither undefined nor null)\nShort-circuiting\nLike the 'OR' and 'AND' logical operators, the right-hand side expression is not evaluated if the left-hand side proves to be neither null\nnor undefined\n.\nfunction a() {\nconsole.log(\"a was called\");\nreturn undefined;\n}\nfunction b() {\nconsole.log(\"b was called\");\nreturn false;\n}\nfunction c() {\nconsole.log(\"c was called\");\nreturn \"foo\";\n}\nconsole.log(a() ?? c());\n// Logs \"a was called\" then \"c was called\" and then \"foo\"\n// as a() returned undefined so both expressions are evaluated\nconsole.log(b() ?? c());\n// Logs \"b was called\" then \"false\"\n// as b() returned false (and not null or undefined), the right\n// hand side expression was not evaluated\nRelationship with the optional chaining operator (?.)\nThe nullish coalescing operator treats undefined\nand null\nas specific values. So does the optional chaining operator (?.\n), which is useful to access a property of an object which may be null\nor undefined\n. Combining them, you can safely access a property of an object which may be nullish and provide a default value if it is.\nconst foo = { someFooProp: \"hi\" };\nconsole.log(foo.someFooProp?.toUpperCase() ?? \"not available\"); // \"HI\"\nconsole.log(foo.someBarProp?.toUpperCase() ?? \"not available\"); // \"not available\"\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # prod-CoalesceExpression |", "code_snippets": ["const foo = null ?? \"default string\";\nconsole.log(foo);\n// Expected output: \"default string\"\n\nconst baz = 0 ?? 42;\nconsole.log(baz);\n// Expected output: 0\n", "leftExpr ?? rightExpr\n", "null || undefined ?? \"foo\"; // raises a SyntaxError\ntrue && undefined ?? \"foo\"; // raises a SyntaxError\n", "(null || undefined) ?? \"foo\"; // returns \"foo\"\n", "const nullValue = null;\nconst emptyText = \"\"; // falsy\nconst someNumber = 42;\n\nconst valA = nullValue ?? \"default for A\";\nconst valB = emptyText ?? \"default for B\";\nconst valC = someNumber ?? 0;\n\nconsole.log(valA); // \"default for A\"\nconsole.log(valB); // \"\" (as the empty string is not null or undefined)\nconsole.log(valC); // 42\n", "let foo;\n\n// foo is never assigned any value so it is still undefined\nconst someDummyText = foo || \"Hello!\";\n", "const count = 0;\nconst text = \"\";\n\nconst qty = count || 42;\nconst message = text || \"hi!\";\nconsole.log(qty); // 42 and not 0\nconsole.log(message); // \"hi!\" and not \"\"\n", "const myText = \"\"; // An empty string (which is also a falsy value)\n\nconst notFalsyText = myText || \"Hello world\";\nconsole.log(notFalsyText); // Hello world\n\nconst preservingFalsy = myText ?? \"Hi neighborhood\";\nconsole.log(preservingFalsy); // '' (as myText is neither undefined nor null)\n", "function a() {\n console.log(\"a was called\");\n return undefined;\n}\nfunction b() {\n console.log(\"b was called\");\n return false;\n}\nfunction c() {\n console.log(\"c was called\");\n return \"foo\";\n}\n\nconsole.log(a() ?? c());\n// Logs \"a was called\" then \"c was called\" and then \"foo\"\n// as a() returned undefined so both expressions are evaluated\n\nconsole.log(b() ?? c());\n// Logs \"b was called\" then \"false\"\n// as b() returned false (and not null or undefined), the right\n// hand side expression was not evaluated\n", "const foo = { someFooProp: \"hi\" };\n\nconsole.log(foo.someFooProp?.toUpperCase() ?? \"not available\"); // \"HI\"\nconsole.log(foo.someBarProp?.toUpperCase() ?? \"not available\"); // \"not available\"\n"], "language": "JavaScript", "source": "mdn", "token_count": 1622} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Duration/sign", "title": "Temporal.Duration.prototype.sign", "content": "Temporal.Duration.prototype.sign\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe sign\naccessor property of Temporal.Duration\ninstances returns 1\nif this duration is positive, -1\nif negative, and 0\nif zero. Because a duration never has mixed signs, the sign of a duration is determined by the sign of any of its non-zero fields.\nExamples\nUsing sign\njs\nconst d1 = Temporal.Duration.from({ hours: 1, minutes: 30 });\nconst d2 = Temporal.Duration.from({ hours: -1, minutes: -30 });\nconst d3 = Temporal.Duration.from({ hours: 0 });\nconsole.log(d1.sign); // 1\nconsole.log(d2.sign); // -1\nconsole.log(d3.sign); // 0\nconsole.log(d1.abs().sign); // 1\nconsole.log(d2.abs().sign); // 1\nconsole.log(d3.abs().sign); // 0\nconsole.log(d1.negated().sign); // -1\nconsole.log(d2.negated().sign); // 1\nconsole.log(d3.negated().sign); // 0\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-get-temporal.duration.prototype.sign |", "code_snippets": ["const d1 = Temporal.Duration.from({ hours: 1, minutes: 30 });\nconst d2 = Temporal.Duration.from({ hours: -1, minutes: -30 });\nconst d3 = Temporal.Duration.from({ hours: 0 });\n\nconsole.log(d1.sign); // 1\nconsole.log(d2.sign); // -1\nconsole.log(d3.sign); // 0\n\nconsole.log(d1.abs().sign); // 1\nconsole.log(d2.abs().sign); // 1\nconsole.log(d3.abs().sign); // 0\n\nconsole.log(d1.negated().sign); // -1\nconsole.log(d2.negated().sign); // 1\nconsole.log(d3.negated().sign); // 0\n"], "language": "JavaScript", "source": "mdn", "token_count": 364} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Symbol.toPrimitive/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/date/symbol.toprimitive/index.md\n\n# Original Wiki contributors\nmfuji09\nchrisdavidmills\nfscholz\nSphinxKnight\nwuqiu\nDelapouite\neduardoboucas\narai\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 68} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/object/tostring/index.md\n\n# Original Wiki contributors\nmfuji09\nninevra\nbrianebert\nAnonymous\nwbamberg\nfscholz\nZearin_Galaurum\nDariaManko\nRainSlide\nDelapouite\njameshkramer\nvermaslal\neduardoboucas\nchrisfillmore\njsx\njajang20\nMingun\nSheppy\nethertank\ntrevorh\ntokuhirom\nevilpie\nWyvernoid\nSevenspade\nMgjbot\nNickolay\nTaken\nMaian\nMarcoos\nDria\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 115} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/resolvedOptions", "title": "Intl.ListFormat.prototype.resolvedOptions()", "content": "Intl.ListFormat.prototype.resolvedOptions()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since April 2021.\nThe resolvedOptions()\nmethod of Intl.ListFormat\ninstances returns a new object with properties reflecting the options computed during initialization of this ListFormat\nobject.\nTry it\nconst deListFormatter = new Intl.ListFormat(\"de-DE\", { type: \"disjunction\" });\nconst options = deListFormatter.resolvedOptions();\nconsole.log(options.locale);\n// Expected output: \"de-DE\"\nconsole.log(options.style);\n// Expected output: \"long\"\nconsole.log(options.type);\n// Expected output: \"disjunction\"\nSyntax\nresolvedOptions()\nParameters\nNone.\nReturn value\nA new object with properties reflecting the options computed during the initialization of this ListFormat\nobject. The object has the following properties, in the order they are listed:\nlocale\n-\nThe BCP 47 language tag for the locale actually used, determined by the locale negotiation process. No Unicode extension key will be included in the output.\ntype\n-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is either\"conjunction\"\n,\"disjunction\"\n, or\"unit\"\n. The default is\"conjunction\"\n. style\n-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is either\"long\"\n,\"short\"\n, or\"narrow\"\n. The default is\"long\"\n.\nExamples\nUsing resolvedOptions\nconst deListFormatter = new Intl.ListFormat(\"de-DE\", { style: \"short\" });\nconst usedOptions = de.resolvedOptions();\nconsole.log(usedOptions.locale); // \"de-DE\"\nconsole.log(usedOptions.style); // \"short\"\nconsole.log(usedOptions.type); // \"conjunction\" (the default value)\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # sec-Intl.ListFormat.prototype.resolvedoptions |", "code_snippets": ["const deListFormatter = new Intl.ListFormat(\"de-DE\", { type: \"disjunction\" });\nconst options = deListFormatter.resolvedOptions();\n\nconsole.log(options.locale);\n// Expected output: \"de-DE\"\n\nconsole.log(options.style);\n// Expected output: \"long\"\n\nconsole.log(options.type);\n// Expected output: \"disjunction\"\n", "resolvedOptions()\n", "const deListFormatter = new Intl.ListFormat(\"de-DE\", { style: \"short\" });\n\nconst usedOptions = de.resolvedOptions();\nconsole.log(usedOptions.locale); // \"de-DE\"\nconsole.log(usedOptions.style); // \"short\"\nconsole.log(usedOptions.type); // \"conjunction\" (the default value)\n"], "language": "JavaScript", "source": "mdn", "token_count": 625} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name", "title": "Function: name", "content": "Function: name\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since August 2016.\nThe name\ndata property of a Function\ninstance indicates the function's name as specified when it was created, or it may be either anonymous\nor ''\n(an empty string) for functions created anonymously.\nTry it\nconst func1 = function () {};\nconst object = {\nfunc2: function () {},\n};\nconsole.log(func1.name);\n// Expected output: \"func1\"\nconsole.log(object.func2.name);\n// Expected output: \"func2\"\nValue\nA string.\nProperty attributes of Function: name | |\n|---|---|\n| Writable | no |\n| Enumerable | no |\n| Configurable | yes |\nNote:\nIn non-standard, pre-ES2015 implementations the configurable\nattribute was false\nas well.\nDescription\nThe function's name\nproperty can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself.\nThe name\nproperty is read-only and cannot be changed by the assignment operator:\nfunction someFunction() {}\nsomeFunction.name = \"otherFunction\";\nconsole.log(someFunction.name); // someFunction\nTo change it, use Object.defineProperty()\n.\nThe name\nproperty is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred.\nFunction declaration\nThe name\nproperty returns the name of a function declaration.\nfunction doSomething() {}\ndoSomething.name; // \"doSomething\"\nDefault-exported function declaration\nAn export default\ndeclaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is \"default\"\n.\n// -- someModule.js --\nexport default function () {}\n// -- main.js --\nimport someModule from \"./someModule.js\";\nsomeModule.name; // \"default\"\nFunction constructor\nFunctions created with the Function()\nconstructor have name \"anonymous\".\nnew Function().name; // \"anonymous\"\nFunction expression\nIf the function expression is named, that name is used as the name\nproperty.\nconst someFunction = function someFunctionName() {};\nsomeFunction.name; // \"someFunctionName\"\nAnonymous function expressions, created using either the function\nkeyword or the arrow function syntax, have \"\"\n(an empty string) as their name by default.\n(function () {}).name; // \"\"\n(() => {}).name; // \"\"\nHowever, such cases are rare \u2014 usually, in order to call the function elsewhere, the function expression is associated with an identifier. The name of an anonymous function expression can be inferred within certain syntactic contexts, including: variable declaration, method, initializer, and default value.\nOne practical case where the name cannot be inferred is a function returned from another function:\nfunction getFoo() {\nreturn () => {};\n}\ngetFoo().name; // \"\"\nVariable declaration and method\nVariables and methods can infer the name of an anonymous function from its syntactic position.\nconst f = function () {};\nconst object = {\nsomeMethod: function () {},\n};\nconsole.log(f.name); // \"f\"\nconsole.log(object.someMethod.name); // \"someMethod\"\nThe same applies to assignment:\nlet f;\nf = () => {};\nf.name; // \"f\"\nInitializer and default value\nFunctions in initializers (default values) of destructuring, default parameters, class fields, etc., will inherit the name of the bound identifier as their name\n.\nconst [f = () => {}] = [];\nf.name; // \"f\"\nconst { someMethod: m = () => {} } = {};\nm.name; // \"m\"\nfunction foo(f = () => {}) {\nconsole.log(f.name);\n}\nfoo(); // \"f\"\nclass Foo {\nstatic someMethod = () => {};\n}\nFoo.someMethod.name; // someMethod\nShorthand method\nconst o = {\nfoo() {},\n};\no.foo.name; // \"foo\";\nBound function\nFunction.prototype.bind()\nproduces a function whose name is \"bound \" plus the function name.\nfunction foo() {}\nfoo.bind({}).name; // \"bound foo\"\nGetter and setter\nWhen using get\nand set\naccessor properties, \"get\" or \"set\" will appear in the function name.\nconst o = {\nget foo() {\nreturn 1;\n},\nset foo(x) {},\n};\nconst descriptor = Object.getOwnPropertyDescriptor(o, \"foo\");\ndescriptor.get.name; // \"get foo\"\ndescriptor.set.name; // \"set foo\";\nClass\nA class's name follows the same algorithm as function declarations and expressions.\nclass Foo {}\nFoo.name; // \"Foo\"\nWarning:\nJavaScript will set the function's name\nproperty only if a function does not have an own property called name\n. However, classes' static members will be set as own properties of the class constructor function, and thus prevent the built-in name\nfrom being applied. See an example below.\nSymbol as function name\nIf a Symbol\nis used a function name and the symbol has a description, the method's name is the description in square brackets.\nconst sym1 = Symbol(\"foo\");\nconst sym2 = Symbol();\nconst o = {\n[sym1]() {},\n[sym2]() {},\n};\no[sym1].name; // \"[foo]\"\no[sym2].name; // \"[]\"\nPrivate fields and methods\nPrivate fields and private methods have the hash (#\n) as part of their names.\nclass Foo {\n#field = () => {};\n#method() {}\ngetNames() {\nconsole.log(this.#field.name);\nconsole.log(this.#method.name);\n}\n}\nnew Foo().getNames();\n// \"#field\"\n// \"#method\"\nExamples\nTelling the constructor name of an object\nYou can use obj.constructor.name\nto check the \"class\" of an object.\nfunction Foo() {} // Or: class Foo {}\nconst fooInstance = new Foo();\nconsole.log(fooInstance.constructor.name); // \"Foo\"\nHowever, because static members will become own properties of the class, we can't obtain the class name for virtually any class with a static method property name()\n:\nclass Foo {\nconstructor() {}\nstatic name() {}\n}\nWith a static name()\nmethod Foo.name\nno longer holds the actual class name but a reference to the name()\nfunction object. Trying to obtain the class of fooInstance\nvia fooInstance.constructor.name\nwon't give us the class name at all, but instead a reference to the static class method. Example:\nconst fooInstance = new Foo();\nconsole.log(fooInstance.constructor.name); // \u0192 name() {}\nDue to the existence of static fields, name\nmay not be a function either.\nclass Foo {\nstatic name = 123;\n}\nconsole.log(new Foo().constructor.name); // 123\nIf a class has a static property called name\n, it will also become writable. The built-in definition in the absence of a custom static definition is read-only:\nFoo.name = \"Hello\";\nconsole.log(Foo.name); // \"Hello\" if class Foo has a static \"name\" property, but \"Foo\" if not.\nTherefore you may not rely on the built-in name\nproperty to always hold a class's name.\nJavaScript compressors and minifiers\nWarning:\nBe careful when using the name\nproperty with source-code transformations, such as those carried out by JavaScript compressors (minifiers) or obfuscators. These tools are often used as part of a JavaScript build pipeline to reduce the size of a program prior to deploying it to production. Such transformations often change a function's name at build time.\nSource code such as:\nfunction Foo() {}\nconst foo = new Foo();\nif (foo.constructor.name === \"Foo\") {\nconsole.log(\"'foo' is an instance of 'Foo'\");\n} else {\nconsole.log(\"Oops!\");\n}\nmay be compressed to:\nfunction a() {}\nconst b = new a();\nif (b.constructor.name === \"Foo\") {\nconsole.log(\"'foo' is an instance of 'Foo'\");\n} else {\nconsole.log(\"Oops!\");\n}\nIn the uncompressed version, the program runs into the truthy branch and logs \"'foo' is an instance of 'Foo'\" \u2014 whereas, in the compressed version it behaves differently, and runs into the else branch. If you rely on the name\nproperty, like in the example above, make sure your build pipeline doesn't change function names, or don't assume a function has a particular name.\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-function-instances-name |", "code_snippets": ["const func1 = function () {};\n\nconst object = {\n func2: function () {},\n};\n\nconsole.log(func1.name);\n// Expected output: \"func1\"\n\nconsole.log(object.func2.name);\n// Expected output: \"func2\"\n", "function someFunction() {}\n\nsomeFunction.name = \"otherFunction\";\nconsole.log(someFunction.name); // someFunction\n", "function doSomething() {}\ndoSomething.name; // \"doSomething\"\n", "// -- someModule.js --\nexport default function () {}\n\n// -- main.js --\nimport someModule from \"./someModule.js\";\n\nsomeModule.name; // \"default\"\n", "new Function().name; // \"anonymous\"\n", "const someFunction = function someFunctionName() {};\nsomeFunction.name; // \"someFunctionName\"\n", "(function () {}).name; // \"\"\n(() => {}).name; // \"\"\n", "function getFoo() {\n return () => {};\n}\ngetFoo().name; // \"\"\n", "const f = function () {};\nconst object = {\n someMethod: function () {},\n};\n\nconsole.log(f.name); // \"f\"\nconsole.log(object.someMethod.name); // \"someMethod\"\n", "let f;\nf = () => {};\nf.name; // \"f\"\n", "const [f = () => {}] = [];\nf.name; // \"f\"\n\nconst { someMethod: m = () => {} } = {};\nm.name; // \"m\"\n\nfunction foo(f = () => {}) {\n console.log(f.name);\n}\nfoo(); // \"f\"\n\nclass Foo {\n static someMethod = () => {};\n}\nFoo.someMethod.name; // someMethod\n", "const o = {\n foo() {},\n};\no.foo.name; // \"foo\";\n", "function foo() {}\nfoo.bind({}).name; // \"bound foo\"\n", "const o = {\n get foo() {\n return 1;\n },\n set foo(x) {},\n};\n\nconst descriptor = Object.getOwnPropertyDescriptor(o, \"foo\");\ndescriptor.get.name; // \"get foo\"\ndescriptor.set.name; // \"set foo\";\n", "class Foo {}\nFoo.name; // \"Foo\"\n", "const sym1 = Symbol(\"foo\");\nconst sym2 = Symbol();\n\nconst o = {\n [sym1]() {},\n [sym2]() {},\n};\n\no[sym1].name; // \"[foo]\"\no[sym2].name; // \"[]\"\n", "class Foo {\n #field = () => {};\n #method() {}\n getNames() {\n console.log(this.#field.name);\n console.log(this.#method.name);\n }\n}\n\nnew Foo().getNames();\n// \"#field\"\n// \"#method\"\n", "function Foo() {} // Or: class Foo {}\n\nconst fooInstance = new Foo();\nconsole.log(fooInstance.constructor.name); // \"Foo\"\n", "class Foo {\n constructor() {}\n static name() {}\n}\n", "const fooInstance = new Foo();\nconsole.log(fooInstance.constructor.name); // \u0192 name() {}\n", "class Foo {\n static name = 123;\n}\nconsole.log(new Foo().constructor.name); // 123\n", "Foo.name = \"Hello\";\nconsole.log(Foo.name); // \"Hello\" if class Foo has a static \"name\" property, but \"Foo\" if not.\n", "function Foo() {}\nconst foo = new Foo();\n\nif (foo.constructor.name === \"Foo\") {\n console.log(\"'foo' is an instance of 'Foo'\");\n} else {\n console.log(\"Oops!\");\n}\n", "function a() {}\nconst b = new a();\nif (b.constructor.name === \"Foo\") {\n console.log(\"'foo' is an instance of 'Foo'\");\n} else {\n console.log(\"Oops!\");\n}\n"], "language": "JavaScript", "source": "mdn", "token_count": 2591} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format", "title": "Intl.DateTimeFormat.prototype.format()", "content": "Intl.DateTimeFormat.prototype.format()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since September 2017.\nThe format()\nmethod of Intl.DateTimeFormat\ninstances formats a date according to the locale and formatting options of this Intl.DateTimeFormat\nobject.\nTry it\nconst options = {\nweekday: \"long\",\nyear: \"numeric\",\nmonth: \"long\",\nday: \"numeric\",\n};\nconst date = new Date(2012, 5);\nconst dateTimeFormat1 = new Intl.DateTimeFormat(\"sr-RS\", options);\nconsole.log(dateTimeFormat1.format(date));\n// Expected output: \"\u043f\u0435\u0442\u0430\u043a, 1. \u0458\u0443\u043d 2012.\"\nconst dateTimeFormat2 = new Intl.DateTimeFormat(\"en-GB\", options);\nconsole.log(dateTimeFormat2.format(date));\n// Expected output: \"Friday, 1 June 2012\"\nconst dateTimeFormat3 = new Intl.DateTimeFormat(\"en-US\", options);\nconsole.log(dateTimeFormat3.format(date));\n// Expected output: \"Friday, June 1, 2012\"\nSyntax\nformat(date)\nParameters\ndate\n-\nThe date to format. Can be a\nDate\norTemporal.PlainDateTime\nobject. Additionally can be aTemporal.PlainTime\n,Temporal.PlainDate\n,Temporal.PlainYearMonth\n, orTemporal.PlainMonthDay\nobject if theDateTimeFormat\nobject was configured to print at least one relevant part of the date.Note: A\nTemporal.ZonedDateTime\nobject will always throw aTypeError\n; useTemporal.ZonedDateTime.prototype.toLocaleString()\nor convert it to aTemporal.PlainDateTime\nobject instead.Omitting it results in formatting the current date (as returned by\nDate.now()\n), which could be slightly confusing, so it is advisable to always explicitly pass a date.\nReturn value\nA string representing the given date\nformatted according to the locale and formatting options of this Intl.DateTimeFormat\nobject.\nNote:\nMost of the time, the formatting returned by format()\nis consistent. However, the output may vary between implementations, even within the same locale \u2014 output variations are by design and allowed by the specification. It may also not be what you expect. For example, the string may use non-breaking spaces or be surrounded by bidirectional control characters. You should not compare the results of format()\nto hardcoded constants.\nExamples\nUsing format\nUse the format\ngetter function for formatting a single date, here for\nSerbia:\nconst options = {\nweekday: \"long\",\nyear: \"numeric\",\nmonth: \"long\",\nday: \"numeric\",\n};\nconst dateTimeFormat = new Intl.DateTimeFormat(\"sr-RS\", options);\nconsole.log(dateTimeFormat.format(new Date()));\n// \"\u043d\u0435\u0434\u0435\u0459\u0430, 7. \u0430\u043f\u0440\u0438\u043b 2013.\"\nUsing format with map\nUse the format\ngetter function for formatting all dates in an array. Note\nthat the function is bound to the Intl.DateTimeFormat\nfrom which it was obtained, so it can be passed directly to\nArray.prototype.map()\n.\nconst a = [new Date(2012, 8), new Date(2012, 11), new Date(2012, 3)];\nconst options = { year: \"numeric\", month: \"long\" };\nconst dateTimeFormat = new Intl.DateTimeFormat(\"pt-BR\", options);\nconst formatted = a.map(dateTimeFormat.format);\nconsole.log(formatted.join(\"; \"));\n// \"setembro de 2012; dezembro de 2012; abril de 2012\"\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # sec-intl.datetimeformat.prototype.format |", "code_snippets": ["const options = {\n weekday: \"long\",\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n};\nconst date = new Date(2012, 5);\n\nconst dateTimeFormat1 = new Intl.DateTimeFormat(\"sr-RS\", options);\nconsole.log(dateTimeFormat1.format(date));\n// Expected output: \"\u043f\u0435\u0442\u0430\u043a, 1. \u0458\u0443\u043d 2012.\"\n\nconst dateTimeFormat2 = new Intl.DateTimeFormat(\"en-GB\", options);\nconsole.log(dateTimeFormat2.format(date));\n// Expected output: \"Friday, 1 June 2012\"\n\nconst dateTimeFormat3 = new Intl.DateTimeFormat(\"en-US\", options);\nconsole.log(dateTimeFormat3.format(date));\n// Expected output: \"Friday, June 1, 2012\"\n", "format(date)\n", "const options = {\n weekday: \"long\",\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n};\nconst dateTimeFormat = new Intl.DateTimeFormat(\"sr-RS\", options);\nconsole.log(dateTimeFormat.format(new Date()));\n// \"\u043d\u0435\u0434\u0435\u0459\u0430, 7. \u0430\u043f\u0440\u0438\u043b 2013.\"\n", "const a = [new Date(2012, 8), new Date(2012, 11), new Date(2012, 3)];\nconst options = { year: \"numeric\", month: \"long\" };\nconst dateTimeFormat = new Intl.DateTimeFormat(\"pt-BR\", options);\nconst formatted = a.map(dateTimeFormat.format);\nconsole.log(formatted.join(\"; \"));\n// \"setembro de 2012; dezembro de 2012; abril de 2012\"\n"], "language": "JavaScript", "source": "mdn", "token_count": 1093} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Requires_global_RegExp", "title": "TypeError: matchAll/replaceAll must be called with a global RegExp", "content": "TypeError: matchAll/replaceAll must be called with a global RegExp\nThe JavaScript exception \"TypeError: matchAll/replaceAll must be called with a global RegExp\" occurs when the String.prototype.matchAll()\nor String.prototype.replaceAll()\nmethod is used with a RegExp\nobject that does not have the global\nflag set.\nMessage\nTypeError: String.prototype.matchAll called with a non-global RegExp argument (V8-based) TypeError: String.prototype.replaceAll called with a non-global RegExp argument (V8-based) TypeError: matchAll must be called with a global RegExp (Firefox) TypeError: replaceAll must be called with a global RegExp (Firefox) TypeError: String.prototype.matchAll argument must not be a non-global regular expression (Safari) TypeError: String.prototype.replaceAll argument must not be a non-global regular expression (Safari)\nError type\nTypeError\nWhat went wrong?\nThe String.prototype.matchAll()\nand String.prototype.replaceAll()\nmethods require a RegExp\nobject with the global\nflag set. This flag indicates that the regular expression can match all locations of the input string, instead of stopping at the first match. Although the g\nflag is redundant when using these methods (because these methods always do a global replacement), they are still required to make the intention clear.\nIt's worth noting that the g\nflag validation is done in the matchAll\nand replaceAll\nmethods. If you use the [Symbol.matchAll]()\nmethod of RegExp\ninstead, you won't get this error, but there will only be a single match.\nExamples\nInvalid cases\n\"abc\".matchAll(/./); // TypeError\n\"abc\".replaceAll(/./, \"f\"); // TypeError\nValid cases\nIf you intend to do global matching/replacement: either add the g\nflag, or construct a new RegExp\nobject with the g\nflag, if you want to keep the original regex unchanged.\n[...\"abc\".matchAll(/./g)]; // [[ \"a\" ], [ \"b\" ], [ \"c\" ]]\n\"abc\".replaceAll(/./g, \"f\"); // \"fff\"\nconst existingPattern = /./;\nconst newPattern = new RegExp(\nexistingPattern.source,\n`${existingPattern.flags}g`,\n);\n\"abc\".replaceAll(newPattern, \"f\"); // \"fff\"\nIf you only intend to do a single matching/replacement: use String.prototype.match()\nor String.prototype.replace()\ninstead. You can also use the [Symbol.matchAll]()\nmethod if you want an iterator like matchAll\nreturns that only contains one match, but doing so will be very confusing.\n\"abc\".match(/./); // [ \"a\" ]\n\"abc\".replace(/./, \"f\"); // \"fbc\"\n[..././[Symbol.matchAll](\"abc\")]; // [[ \"a\" ]]", "code_snippets": ["\"abc\".matchAll(/./); // TypeError\n\"abc\".replaceAll(/./, \"f\"); // TypeError\n", "[...\"abc\".matchAll(/./g)]; // [[ \"a\" ], [ \"b\" ], [ \"c\" ]]\n\"abc\".replaceAll(/./g, \"f\"); // \"fff\"\n\nconst existingPattern = /./;\nconst newPattern = new RegExp(\n existingPattern.source,\n `${existingPattern.flags}g`,\n);\n\"abc\".replaceAll(newPattern, \"f\"); // \"fff\"\n", "\"abc\".match(/./); // [ \"a\" ]\n\"abc\".replace(/./, \"f\"); // \"fbc\"\n\n[..././[Symbol.matchAll](\"abc\")]; // [[ \"a\" ]]\n"], "language": "JavaScript", "source": "mdn", "token_count": 724} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE", "title": "Number.MIN_VALUE", "content": "Number.MIN_VALUE\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe Number.MIN_VALUE\nstatic data property represents the smallest positive numeric value representable in JavaScript.\nTry it\nfunction divide(x, y) {\nif (x / y < Number.MIN_VALUE) {\nreturn \"Process as 0\";\n}\nreturn x / y;\n}\nconsole.log(divide(5e-324, 1));\n// Expected output: 5e-324\nconsole.log(divide(5e-324, 2));\n// Expected output: \"Process as 0\"\nValue\n2-1074, or 5E-324\n.\nProperty attributes of Number.MIN_VALUE | |\n|---|---|\n| Writable | no |\n| Enumerable | no |\n| Configurable | no |\nDescription\nNumber.MIN_VALUE\nis the smallest positive number (not the most negative number) that can be represented within float precision \u2014 in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support \u2014 instead the spec says, \"must be the smallest non-zero positive value that can actually be represented by the implementation\". This is because small IEEE-754 floating point numbers are denormalized, but implementations are not required to support this representation, in which case Number.MIN_VALUE\nmay be larger.\nIn practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or 5E-324\n.\nBecause MIN_VALUE\nis a static property of Number\n, you always use it as Number.MIN_VALUE\n, rather than as a property of a number value.\nExamples\nUsing MIN_VALUE\nThe following code divides two numeric values. If the result is greater than or equal to MIN_VALUE\n, the func1\nfunction is called; otherwise, the func2\nfunction is called.\nif (num1 / num2 >= Number.MIN_VALUE) {\nfunc1();\n} else {\nfunc2();\n}\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-number.min_value |", "code_snippets": ["function divide(x, y) {\n if (x / y < Number.MIN_VALUE) {\n return \"Process as 0\";\n }\n return x / y;\n}\n\nconsole.log(divide(5e-324, 1));\n// Expected output: 5e-324\n\nconsole.log(divide(5e-324, 2));\n// Expected output: \"Process as 0\"\n", "if (num1 / num2 >= Number.MIN_VALUE) {\n func1();\n} else {\n func2();\n}\n"], "language": "JavaScript", "source": "mdn", "token_count": 565} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/isRawJSON/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/json/israwjson/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 38} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Duration/nanoseconds", "title": "Temporal.Duration.prototype.nanoseconds", "content": "Temporal.Duration.prototype.nanoseconds\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe nanoseconds\naccessor property of Temporal.Duration\ninstances returns an integer representing the number of nanoseconds in the duration.\nUnless the duration is balanced, you cannot assume the range of this value, but you can know its sign by checking the duration's sign\nproperty. If it is balanced to a unit above nanoseconds, the nanoseconds\nabsolute value will be between 0 and 999, inclusive.\nThe set accessor of nanoseconds\nis undefined\n. You cannot change this property directly. Use the with()\nmethod to create a new Temporal.Duration\nobject with the desired new value.\nExamples\nUsing nanoseconds\njs\nconst d1 = Temporal.Duration.from({ microseconds: 1, nanoseconds: 500 });\nconst d2 = Temporal.Duration.from({ microseconds: -1, nanoseconds: -500 });\nconst d3 = Temporal.Duration.from({ microseconds: 1 });\nconst d4 = Temporal.Duration.from({ nanoseconds: 1000 });\nconsole.log(d1.nanoseconds); // 500\nconsole.log(d2.nanoseconds); // -500\nconsole.log(d3.nanoseconds); // 0\nconsole.log(d4.nanoseconds); // 1000\n// Balance d4\nconst d4Balanced = d4.round({ largestUnit: \"microseconds\" });\nconsole.log(d4Balanced.nanoseconds); // 0\nconsole.log(d4Balanced.microseconds); // 1\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-get-temporal.duration.prototype.nanoseconds |\nBrowser compatibility\nSee also\nTemporal.Duration\nTemporal.Duration.prototype.years\nTemporal.Duration.prototype.months\nTemporal.Duration.prototype.weeks\nTemporal.Duration.prototype.days\nTemporal.Duration.prototype.hours\nTemporal.Duration.prototype.minutes\nTemporal.Duration.prototype.seconds\nTemporal.Duration.prototype.milliseconds\nTemporal.Duration.prototype.microseconds", "code_snippets": ["const d1 = Temporal.Duration.from({ microseconds: 1, nanoseconds: 500 });\nconst d2 = Temporal.Duration.from({ microseconds: -1, nanoseconds: -500 });\nconst d3 = Temporal.Duration.from({ microseconds: 1 });\nconst d4 = Temporal.Duration.from({ nanoseconds: 1000 });\n\nconsole.log(d1.nanoseconds); // 500\nconsole.log(d2.nanoseconds); // -500\nconsole.log(d3.nanoseconds); // 0\nconsole.log(d4.nanoseconds); // 1000\n\n// Balance d4\nconst d4Balanced = d4.round({ largestUnit: \"microseconds\" });\nconsole.log(d4Balanced.nanoseconds); // 0\nconsole.log(d4Balanced.microseconds); // 1\n"], "language": "JavaScript", "source": "mdn", "token_count": 595} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/supportedLocalesOf", "title": "Intl.NumberFormat.supportedLocalesOf()", "content": "Intl.NumberFormat.supportedLocalesOf()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since September 2017.\nThe Intl.NumberFormat.supportedLocalesOf()\nstatic method returns an array containing those of the provided locales that are supported in number formatting without having to fall back to the runtime's default locale.\nTry it\nconst locales = [\"ban\", \"id-u-co-pinyin\", \"de-ID\"];\nconst options = { localeMatcher: \"lookup\" };\nconsole.log(Intl.NumberFormat.supportedLocalesOf(locales, options));\n// Expected output: Array [\"id-u-co-pinyin\", \"de-ID\"]\n// (Note: the exact output may be browser-dependent)\nSyntax\nIntl.NumberFormat.supportedLocalesOf(locales)\nIntl.NumberFormat.supportedLocalesOf(locales, options)\nParameters\nlocales\n-\nA string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the\nlocales\nargument, see the parameter description on theIntl\nmain page. options\nOptional-\nAn object that may have the following property:\nlocaleMatcher\n-\nThe locale matching algorithm to use. Possible values are\n\"lookup\"\nand\"best fit\"\n; the default is\"best fit\"\n. For information about this option, see the Intl page.\nReturn value\nAn array of strings representing a subset of the given locale tags that are supported in number formatting without having to fall back to the runtime's default locale.\nExamples\nUsing supportedLocalesOf()\nAssuming a runtime that supports Indonesian and German but not Balinese in number formatting, supportedLocalesOf\nreturns the Indonesian and German language tags unchanged, even though pinyin\ncollation is neither relevant to number formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the \"lookup\"\nalgorithm here \u2014 a \"best fit\"\nmatcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.\nconst locales = [\"ban\", \"id-u-co-pinyin\", \"de-ID\"];\nconst options = { localeMatcher: \"lookup\" };\nconsole.log(Intl.NumberFormat.supportedLocalesOf(locales, options));\n// [\"id-u-co-pinyin\", \"de-ID\"]\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # sec-intl.numberformat.supportedlocalesof |", "code_snippets": ["const locales = [\"ban\", \"id-u-co-pinyin\", \"de-ID\"];\nconst options = { localeMatcher: \"lookup\" };\n\nconsole.log(Intl.NumberFormat.supportedLocalesOf(locales, options));\n// Expected output: Array [\"id-u-co-pinyin\", \"de-ID\"]\n// (Note: the exact output may be browser-dependent)\n", "Intl.NumberFormat.supportedLocalesOf(locales)\nIntl.NumberFormat.supportedLocalesOf(locales, options)\n", "const locales = [\"ban\", \"id-u-co-pinyin\", \"de-ID\"];\nconst options = { localeMatcher: \"lookup\" };\nconsole.log(Intl.NumberFormat.supportedLocalesOf(locales, options));\n// [\"id-u-co-pinyin\", \"de-ID\"]\n"], "language": "JavaScript", "source": "mdn", "token_count": 744} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/resolvedOptions", "title": "Intl.NumberFormat.prototype.resolvedOptions()", "content": "Intl.NumberFormat.prototype.resolvedOptions()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since September 2017.\nThe resolvedOptions()\nmethod of Intl.NumberFormat\ninstances returns a new object with properties reflecting the options computed during initialization of this NumberFormat\nobject.\nTry it\nconst numberFormat = new Intl.NumberFormat(\"de-DE\");\nconst options = numberFormat.resolvedOptions();\nconsole.log(options.locale);\n// Expected output: \"de-DE\"\nconsole.log(options.numberingSystem);\n// Expected output: \"latn\"\nconsole.log(options.style);\n// Expected output: \"decimal\"\nSyntax\nresolvedOptions()\nParameters\nNone.\nReturn value\nA new object with properties reflecting the options computed during the initialization of this NumberFormat\nobject. The object has the following properties, in the order they are listed:\nlocale\n-\nThe BCP 47 language tag for the locale actually used, determined by the locale negotiation process. Only the\nnu\nUnicode extension key, if requested, may be included in the output. numberingSystem\n-\nThe value provided for this property in the\noptions\nargument, or using the Unicode extension key\"nu\"\n, with default filled in as needed. It is a supported numbering system for this locale. The default is locale dependent. style\n-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is either\"decimal\"\n,\"percent\"\n,\"currency\"\n, or\"unit\"\n. The default is\"decimal\"\n. currency\nOptional-\nThe value provided for this property in the\noptions\nargument. It is only present ifstyle\nis\"currency\"\n. It is an ISO 4217 currency code; seeIntl.supportedValuesOf()\n. It is required ifstyle\nis\"currency\"\nso there is no default. currencyDisplay\nOptional-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is only present ifstyle\nis\"currency\"\n. It is either\"code\"\n,\"symbol\"\n,\"narrowSymbol\"\n, or\"name\"\n. The default is\"symbol\"\n. currencySign\nOptional-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is only present ifstyle\nis\"currency\"\n. It is either\"standard\"\nor\"accounting\"\n. The default is\"standard\"\n. unit\nOptional-\nThe value provided for this property in the\noptions\nargument. It is only present ifstyle\nis\"unit\"\n. It is a sanctioned unit identifier from the full CLDR list. It is required ifstyle\nis\"unit\"\nso there is no default. unitDisplay\nOptional-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is only present ifstyle\nis\"unit\"\n. It is either\"short\"\n,\"narrow\"\n, or\"long\"\n. The default is\"short\"\n. minimumIntegerDigits\n-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is an integer between1\nand21\n. The default is1\n. minimumFractionDigits\n,maximumFractionDigits\nOptional-\nThe value provided for these properties in the\noptions\nargument, with defaults filled in as needed. They are only present if necessary; see digit options. It is an integer between0\nand100\n. minimumSignificantDigits\n,maximumSignificantDigits\nOptional-\nThe value provided for these properties in the\noptions\nargument, with defaults filled in as needed. They are only present if necessary; see digit options. It is an integer between1\nand21\n. useGrouping\n-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed, and with some values normalized. It is either\"always\"\n,\"auto\"\n,\"min2\"\n, or the booleanfalse\n. The default is\"min2\"\nifnotation\nis\"compact\"\n, and\"auto\"\notherwise. notation\n-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is either\"standard\"\n,\"scientific\"\n,\"engineering\"\n, or\"compact\"\n. The default is\"standard\"\n. compactDisplay\nOptional-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is only present ifnotation\nis\"compact\"\n. It is either\"short\"\nor\"long\"\n. The default is\"short\"\n. signDisplay\n-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is either\"auto\"\n,\"always\"\n,\"exceptZero\"\n,\"negative\"\n, or\"never\"\n. The default is\"auto\"\n. roundingIncrement\n-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is one of1\n,2\n,5\n,10\n,20\n,25\n,50\n,100\n,200\n,250\n,500\n,1000\n,2000\n,2500\n, and5000\n. The default is1\n. roundingMode\n-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is one of\"ceil\"\n,\"floor\"\n,\"expand\"\n,\"trunc\"\n,\"halfCeil\"\n,\"halfFloor\"\n,\"halfExpand\"\n,\"halfTrunc\"\n, and\"halfEven\"\n. The default is\"halfExpand\"\n. roundingPriority\n-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is either\"auto\"\n,\"morePrecision\"\n, or\"lessPrecision\"\n. The default is\"auto\"\n. trailingZeroDisplay\n-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is either\"auto\"\nor\"stripIfInteger\"\n. The default is\"auto\"\n.\nExamples\nUsing the resolvedOptions\nmethod\n// Create a NumberFormat\nconst de = new Intl.NumberFormat(\"de-DE\", {\nstyle: \"currency\",\ncurrency: \"USD\",\nmaximumFractionDigits: 2,\nroundingIncrement: 5,\nroundingMode: \"halfCeil\",\n});\n// Resolve the options\nconst usedOptions = de.resolvedOptions();\nconsole.log(usedOptions.locale); // \"de-DE\"\nconsole.log(usedOptions.numberingSystem); // \"latn\"\nconsole.log(usedOptions.compactDisplay); // undefined (\"notation\" not set to \"compact\")\nconsole.log(usedOptions.currency); // \"USD\"\nconsole.log(usedOptions.currencyDisplay); // \"symbol\"\nconsole.log(usedOptions.currencySign); // \"standard\"\nconsole.log(usedOptions.minimumIntegerDigits); // 1\nconsole.log(usedOptions.minimumFractionDigits); // 2\nconsole.log(usedOptions.maximumFractionDigits); // 2\nconsole.log(usedOptions.minimumSignificantDigits); // undefined (maximumFractionDigits is set)\nconsole.log(usedOptions.maximumSignificantDigits); // undefined (maximumFractionDigits is set)\nconsole.log(usedOptions.notation); // \"standard\"\nconsole.log(usedOptions.roundingIncrement); // 5\nconsole.log(usedOptions.roundingMode); // halfCeil\nconsole.log(usedOptions.roundingPriority); // auto\nconsole.log(usedOptions.signDisplay); // \"auto\"\nconsole.log(usedOptions.style); // \"currency\"\nconsole.log(usedOptions.trailingZeroDisplay); // auto\nconsole.log(usedOptions.useGrouping); // auto\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # sec-intl.numberformat.prototype.resolvedoptions |", "code_snippets": ["const numberFormat = new Intl.NumberFormat(\"de-DE\");\nconst options = numberFormat.resolvedOptions();\n\nconsole.log(options.locale);\n// Expected output: \"de-DE\"\n\nconsole.log(options.numberingSystem);\n// Expected output: \"latn\"\n\nconsole.log(options.style);\n// Expected output: \"decimal\"\n", "resolvedOptions()\n", "// Create a NumberFormat\nconst de = new Intl.NumberFormat(\"de-DE\", {\n style: \"currency\",\n currency: \"USD\",\n maximumFractionDigits: 2,\n roundingIncrement: 5,\n roundingMode: \"halfCeil\",\n});\n\n// Resolve the options\nconst usedOptions = de.resolvedOptions();\nconsole.log(usedOptions.locale); // \"de-DE\"\nconsole.log(usedOptions.numberingSystem); // \"latn\"\nconsole.log(usedOptions.compactDisplay); // undefined (\"notation\" not set to \"compact\")\nconsole.log(usedOptions.currency); // \"USD\"\nconsole.log(usedOptions.currencyDisplay); // \"symbol\"\nconsole.log(usedOptions.currencySign); // \"standard\"\nconsole.log(usedOptions.minimumIntegerDigits); // 1\nconsole.log(usedOptions.minimumFractionDigits); // 2\nconsole.log(usedOptions.maximumFractionDigits); // 2\nconsole.log(usedOptions.minimumSignificantDigits); // undefined (maximumFractionDigits is set)\nconsole.log(usedOptions.maximumSignificantDigits); // undefined (maximumFractionDigits is set)\nconsole.log(usedOptions.notation); // \"standard\"\nconsole.log(usedOptions.roundingIncrement); // 5\nconsole.log(usedOptions.roundingMode); // halfCeil\nconsole.log(usedOptions.roundingPriority); // auto\nconsole.log(usedOptions.signDisplay); // \"auto\"\nconsole.log(usedOptions.style); // \"currency\"\nconsole.log(usedOptions.trailingZeroDisplay); // auto\nconsole.log(usedOptions.useGrouping); // auto\n"], "language": "JavaScript", "source": "mdn", "token_count": 2071} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Duration/microseconds", "title": "Temporal.Duration.prototype.microseconds", "content": "Temporal.Duration.prototype.microseconds\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe microseconds\naccessor property of Temporal.Duration\ninstances returns an integer representing the number of microseconds in the duration.\nUnless the duration is balanced, you cannot assume the range of this value, but you can know its sign by checking the duration's sign\nproperty. If it is balanced to a unit above microseconds, the microseconds\nabsolute value will be between 0 and 999, inclusive.\nThe set accessor of microseconds\nis undefined\n. You cannot change this property directly. Use the with()\nmethod to create a new Temporal.Duration\nobject with the desired new value.\nExamples\nUsing microseconds\njs\nconst d1 = Temporal.Duration.from({ milliseconds: 1, microseconds: 500 });\nconst d2 = Temporal.Duration.from({ milliseconds: -1, microseconds: -500 });\nconst d3 = Temporal.Duration.from({ milliseconds: 1 });\nconst d4 = Temporal.Duration.from({ microseconds: 1000 });\nconsole.log(d1.microseconds); // 500\nconsole.log(d2.microseconds); // -500\nconsole.log(d3.microseconds); // 0\nconsole.log(d4.microseconds); // 1000\n// Balance d4\nconst d4Balanced = d4.round({ largestUnit: \"milliseconds\" });\nconsole.log(d4Balanced.microseconds); // 0\nconsole.log(d4Balanced.milliseconds); // 1\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-get-temporal.duration.prototype.microseconds |\nBrowser compatibility\nSee also\nTemporal.Duration\nTemporal.Duration.prototype.years\nTemporal.Duration.prototype.months\nTemporal.Duration.prototype.weeks\nTemporal.Duration.prototype.days\nTemporal.Duration.prototype.hours\nTemporal.Duration.prototype.minutes\nTemporal.Duration.prototype.seconds\nTemporal.Duration.prototype.milliseconds\nTemporal.Duration.prototype.nanoseconds", "code_snippets": ["const d1 = Temporal.Duration.from({ milliseconds: 1, microseconds: 500 });\nconst d2 = Temporal.Duration.from({ milliseconds: -1, microseconds: -500 });\nconst d3 = Temporal.Duration.from({ milliseconds: 1 });\nconst d4 = Temporal.Duration.from({ microseconds: 1000 });\n\nconsole.log(d1.microseconds); // 500\nconsole.log(d2.microseconds); // -500\nconsole.log(d3.microseconds); // 0\nconsole.log(d4.microseconds); // 1000\n\n// Balance d4\nconst d4Balanced = d4.round({ largestUnit: \"milliseconds\" });\nconsole.log(d4Balanced.microseconds); // 0\nconsole.log(d4Balanced.milliseconds); // 1\n"], "language": "JavaScript", "source": "mdn", "token_count": 601} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift", "title": "Right shift (>>)", "content": "Right shift (>>)\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe right shift (>>\n) operator returns a number or BigInt whose binary representation is the first operand shifted by the specified number of bits to the right. Excess bits shifted off to the right are discarded, and copies of the leftmost bit are shifted in from the left. This operation is also called \"sign-propagating right shift\" or \"arithmetic right shift\", because the sign of the resulting number is the same as the sign of the first operand.\nTry it\nconst a = 5; // 00000000000000000000000000000101\nconst b = 2; // 00000000000000000000000000000010\nconst c = -5; // 11111111111111111111111111111011\nconsole.log(a >> b); // 00000000000000000000000000000001\n// Expected output: 1\nconsole.log(c >> b); // 11111111111111111111111111111110\n// Expected output: -2\nSyntax\nx >> y\nDescription\nThe >>\noperator is overloaded for two types of operands: number and BigInt. For numbers, the operator returns a 32-bit integer. For BigInts, the operator returns a BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt right shift if both operands become BigInts; otherwise, it converts both operands to 32-bit integers and performs number right shift. A TypeError\nis thrown if one operand becomes a BigInt but the other becomes a number.\nSince the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name \"sign-propagating\".\nThe operator operates on the left operand's bit representation in two's complement. Consider the 32-bit binary representations of the decimal (base 10) numbers 9\nand -9\n:\n9 (base 10): 00000000000000000000000000001001 (base 2) -9 (base 10): 11111111111111111111111111110111 (base 2)\nThe binary representation under two's complement of the negative decimal (base 10) number -9\nis formed by inverting all the bits of its opposite number, which is 9\nand 00000000000000000000000000001001\nin binary, and adding 1\n.\nIn both cases, the sign of the binary number is given by its leftmost bit: for the positive decimal number 9\n, the leftmost bit of the binary representation is 0\n, and for the negative decimal number -9\n, the leftmost bit of the binary representation is 1\n.\nGiven those binary representations of the decimal (base 10) numbers 9\n, and -9\n:\n9 >> 2\nyields 2:\n9 (base 10): 00000000000000000000000000001001 (base 2) -------------------------------- 9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)\nNotice how two rightmost bits, 01\n, have been shifted off, and two copies of the leftmost bit, 0\nhave been shifted in from the left.\n-9 >> 2\nyields -3\n:\n-9 (base 10): 11111111111111111111111111110111 (base 2) -------------------------------- -9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)\nNotice how two rightmost bits, 11\n, have been shifted off. But as far as the leftmost bits: in this case, the leftmost bit is 1\n. So two copies of that leftmost 1\nbit have been shifted in from the left \u2014 which preserves the negative sign.\nThe binary representation 11111111111111111111111111111101\nis equal to the negative decimal (base 10) number -3\n, because all negative integers are stored as two's complements, and this one can be calculated by inverting all the bits of the binary representation of the positive decimal (base 10) number 3\n, which is 00000000000000000000000000000011\n, and then adding one.\nIf the left operand is a number with more than 32 bits, it will get the most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:\nBefore: 11100110111110100000000000000110000000000001 After: 10100000000000000110000000000001\nThe right operand will be converted to an unsigned 32-bit integer and then taken modulo 32, so the actual shift offset will always be a positive integer between 0 and 31, inclusive. For example, 100 >> 32\nis the same as 100 >> 0\n(and produces 100\n) because 32 modulo 32 is 0.\nWarning:\nYou may see people using >> 0\nto truncate numbers to integers. Right shifting any number x\nby 0\nreturns x\nconverted to a 32-bit integer, which additionally removes leading bits for numbers outside the range -2147483648 to 2147483647. Use Math.trunc()\ninstead.\nFor BigInts, there's no truncation. Conceptually, understand positive BigInts as having an infinite number of leading 0\nbits, and negative BigInts having an infinite number of leading 1\nbits.\nExamples\nUsing right shift\n9 >> 2; // 2\n-9 >> 2; // -3\n9n >> 2n; // 2n\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-signed-right-shift-operator |", "code_snippets": ["const a = 5; // 00000000000000000000000000000101\nconst b = 2; // 00000000000000000000000000000010\nconst c = -5; // 11111111111111111111111111111011\n\nconsole.log(a >> b); // 00000000000000000000000000000001\n// Expected output: 1\n\nconsole.log(c >> b); // 11111111111111111111111111111110\n// Expected output: -2\n", "x >> y\n", "9 >> 2; // 2\n-9 >> 2; // -3\n\n9n >> 2n; // 2n\n"], "language": "JavaScript", "source": "mdn", "token_count": 1290} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTemporalInstant", "title": "Date.prototype.toTemporalInstant()", "content": "Date.prototype.toTemporalInstant()\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe toTemporalInstant()\nmethod of Date\ninstances returns a new Temporal.Instant\nobject with the same epochMilliseconds\nvalue as this date's timestamp.\nUse this method to convert legacy Date\nvalues to the Temporal\nAPI, then further convert it to other Temporal\nclasses as necessary.\nSyntax\njs\ntoTemporalInstant()\nParameters\nNone.\nReturn value\nA new Temporal.Instant\nobject with the same epochMilliseconds\nvalue as this date's timestamp. Its microsecond and nanosecond components are always 0\n.\nExceptions\nRangeError\n-\nThrown if the date is invalid (it has a timestamp of\nNaN\n).\nExamples\nUsing toTemporalInstant()\njs\nconst legacyDate = new Date(\"2021-07-01T12:34:56.789Z\");\nconst instant = legacyDate.toTemporalInstant();\n// Further convert it to other objects\nconst zdt = instant.toZonedDateTimeISO(\"UTC\");\nconst date = zdt.toPlainDate();\nconsole.log(date.toString()); // 2021-07-01\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-date.prototype.totemporalinstant |", "code_snippets": ["toTemporalInstant()\n", "const legacyDate = new Date(\"2021-07-01T12:34:56.789Z\");\nconst instant = legacyDate.toTemporalInstant();\n\n// Further convert it to other objects\nconst zdt = instant.toZonedDateTimeISO(\"UTC\");\nconst date = zdt.toPlainDate();\nconsole.log(date.toString()); // 2021-07-01\n"], "language": "JavaScript", "source": "mdn", "token_count": 353} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator", "title": "Intl.Collator() constructor", "content": "Intl.Collator() constructor\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since September 2017.\nThe Intl.Collator()\nconstructor creates Intl.Collator\nobjects.\nTry it\nconsole.log([\"Z\", \"a\", \"z\", \"\u00e4\"].sort(new Intl.Collator(\"de\").compare));\n// Expected output: Array [\"a\", \"\u00e4\", \"z\", \"Z\"]\nconsole.log([\"Z\", \"a\", \"z\", \"\u00e4\"].sort(new Intl.Collator(\"sv\").compare));\n// Expected output: Array [\"a\", \"z\", \"Z\", \"\u00e4\"]\nconsole.log(\n[\"Z\", \"a\", \"z\", \"\u00e4\"].sort(\nnew Intl.Collator(\"de\", { caseFirst: \"upper\" }).compare,\n),\n);\n// Expected output: Array [\"a\", \"\u00e4\", \"Z\", \"z\"]\nSyntax\nnew Intl.Collator()\nnew Intl.Collator(locales)\nnew Intl.Collator(locales, options)\nIntl.Collator()\nIntl.Collator(locales)\nIntl.Collator(locales, options)\nNote:\nIntl.Collator()\ncan be called with or without new\n. Both create a new Intl.Collator\ninstance.\nParameters\nlocales\nOptional-\nA string with a BCP 47 language tag or an\nIntl.Locale\ninstance, or an array of such locale identifiers. The runtime's default locale is used whenundefined\nis passed or when none of the specified locale identifiers is supported. For the general form and interpretation of thelocales\nargument, see the parameter description on theIntl\nmain page.The following Unicode extension keys are allowed:\nThese keys can also be set with\noptions\n(as listed below). When both are set, theoptions\nproperty takes precedence. options\nOptional-\nAn object containing the following properties, in the order they are retrieved (all of them are optional):\nusage\n-\nWhether the comparison is for sorting a list of strings or fuzzy (for the Latin script diacritic-insensitive and case-insensitive) filtering a list of strings by key. Possible values are:\n\"sort\"\n(default)-\nFor sorting a list of strings.\n\"search\"\n-\nFor filtering a list of strings by testing each list item for a full-string match against a key. With\n\"search\"\n, the caller should only pay attention to whethercompare()\nreturns zero or non-zero and should not distinguish the non-zero return values from each other. That is, it is inappropriate to use\"search\"\nfor sorting/ordering.\nlocaleMatcher\n-\nThe locale matching algorithm to use. Possible values are\n\"lookup\"\nand\"best fit\"\n; the default is\"best fit\"\n. For information about this option, see Locale identification and negotiation. collation\n-\nVariant collations for certain locales, such as\n\"emoji\"\n,\"pinyin\"\n,\"stroke\"\n, and so on. Only has an effect whenusage\nis\"sort\"\n(because\"search\"\nis underlyingly its own collation type). For a list of supported collation types, seeIntl.supportedValuesOf()\n; the default is\"default\"\n. This option can also be set through theco\nUnicode extension key; if both are provided, thisoptions\nproperty takes precedence. numeric\n-\nWhether numeric collation should be used, such that \"1\" < \"2\" < \"10\". Possible values are\ntrue\nandfalse\n; the default isfalse\n. This option can also be set through thekn\nUnicode extension key; if both are provided, thisoptions\nproperty takes precedence. caseFirst\n-\nWhether upper case or lower case should sort first. Possible values are\n\"upper\"\n,\"lower\"\n, and\"false\"\n(use the locale's default); the default is\"false\"\n. This option can also be set through thekf\nUnicode extension key; if both are provided, thisoptions\nproperty takes precedence. sensitivity\n-\nWhich differences in the strings should lead to non-zero result values. Possible values are:\n\"base\"\n-\nOnly strings that differ in base letters compare as unequal. Examples: a \u2260 b, a = \u00e1, a = A. In the Unicode collation algorithm, this is equivalent to the primary strength level.\n\"accent\"\n-\nOnly strings that differ in base letters or accents and other diacritic marks compare as unequal. Examples: a \u2260 b, a \u2260 \u00e1, a = A. In the Unicode collation algorithm, this is equivalent to the secondary strength level.\n\"case\"\n-\nOnly strings that differ in base letters or case compare as unequal. Examples: a \u2260 b, a = \u00e1, a \u2260 A. In the Unicode collation algorithm, this is equivalent to the primary strength level with case level handling.\n\"variant\"\n-\nStrings that differ in base letters, accents and other diacritic marks, or case compare as unequal. Other differences may also be taken into consideration. Examples: a \u2260 b, a \u2260 \u00e1, a \u2260 A. In the Unicode collation algorithm, this is equivalent to the tertiary strength level.\nThe default is\n\"variant\"\nfor usage\"sort\"\n; it's locale dependent for usage\"search\"\nper spec, but is usually also\"variant\"\n. Because the core functionality of\"search\"\nis accent-insensitive and case-insensitive filtering, setting it to\"base\"\nmakes the most sense (and perhaps\"case\"\n). ignorePunctuation\n-\nWhether punctuation should be ignored. Possible values are\ntrue\nandfalse\n. The default istrue\nfor Thai (th\n) andfalse\nfor all other languages.\nExceptions\nRangeError\n-\nThrown if\nlocales\noroptions\ncontain invalid values.\nExamples\nUsing Collator\nThe following example demonstrates the different potential results for a string occurring before, after, or at the same level as another:\nconsole.log(new Intl.Collator().compare(\"a\", \"c\")); // -1, or some other negative value\nconsole.log(new Intl.Collator().compare(\"c\", \"a\")); // 1, or some other positive value\nconsole.log(new Intl.Collator().compare(\"a\", \"a\")); // 0\nNote that the results shown in the code above can vary between browsers and browser versions. This is because the values are implementation-specific. That is, the specification requires only that the before and after values are negative and positive.\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # sec-intl-collator-constructor |", "code_snippets": ["console.log([\"Z\", \"a\", \"z\", \"\u00e4\"].sort(new Intl.Collator(\"de\").compare));\n// Expected output: Array [\"a\", \"\u00e4\", \"z\", \"Z\"]\n\nconsole.log([\"Z\", \"a\", \"z\", \"\u00e4\"].sort(new Intl.Collator(\"sv\").compare));\n// Expected output: Array [\"a\", \"z\", \"Z\", \"\u00e4\"]\n\nconsole.log(\n [\"Z\", \"a\", \"z\", \"\u00e4\"].sort(\n new Intl.Collator(\"de\", { caseFirst: \"upper\" }).compare,\n ),\n);\n// Expected output: Array [\"a\", \"\u00e4\", \"Z\", \"z\"]\n", "new Intl.Collator()\nnew Intl.Collator(locales)\nnew Intl.Collator(locales, options)\n\nIntl.Collator()\nIntl.Collator(locales)\nIntl.Collator(locales, options)\n", "console.log(new Intl.Collator().compare(\"a\", \"c\")); // -1, or some other negative value\nconsole.log(new Intl.Collator().compare(\"c\", \"a\")); // 1, or some other positive value\nconsole.log(new Intl.Collator().compare(\"a\", \"a\")); // 0\n"], "language": "JavaScript", "source": "mdn", "token_count": 1615} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Now/plainDateTimeISO", "title": "Temporal.Now.plainDateTimeISO()", "content": "Temporal.Now.plainDateTimeISO()\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe Temporal.Now.plainDateTimeISO()\nstatic method returns the current date and time as a Temporal.PlainDateTime\nobject, in the ISO 8601 calendar and the specified time zone.\nSyntax\nTemporal.Now.plainDateTimeISO()\nTemporal.Now.plainDateTimeISO(timeZone)\nParameters\ntimeZone\nOptional-\nEither a string or a\nTemporal.ZonedDateTime\ninstance representing the time zone to interpret the system time in. If aTemporal.ZonedDateTime\ninstance, 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).\nReturn value\nThe current date and time in the specified time zone, as a Temporal.PlainDateTime\nobject using the ISO 8601 calendar. Has the same precision as Temporal.Now.instant()\n.\nExceptions\nRangeError\n-\nThrown if the time zone is invalid.\nExamples\nUsing Temporal.Now.plainDateTimeISO()\n// The current date and time in the system's time zone\nconst dateTime = Temporal.Now.plainDateTimeISO();\nconsole.log(dateTime); // e.g.: 2021-10-01T06:12:34.567890123\n// The current date and time in the \"America/New_York\" time zone\nconst dateTimeInNewYork = Temporal.Now.plainDateTimeISO(\"America/New_York\");\nconsole.log(dateTimeInNewYork); // e.g.: 2021-09-30T23:12:34.567890123\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-temporal.now.plaindatetimeiso |", "code_snippets": ["Temporal.Now.plainDateTimeISO()\nTemporal.Now.plainDateTimeISO(timeZone)\n", "// The current date and time in the system's time zone\nconst dateTime = Temporal.Now.plainDateTimeISO();\nconsole.log(dateTime); // e.g.: 2021-10-01T06:12:34.567890123\n\n// The current date and time in the \"America/New_York\" time zone\nconst dateTimeInNewYork = Temporal.Now.plainDateTimeISO(\"America/New_York\");\nconsole.log(dateTimeInNewYork); // e.g.: 2021-09-30T23:12:34.567890123\n"], "language": "JavaScript", "source": "mdn", "token_count": 504} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/string/length/index.md\n\n# Original Wiki contributors\nbuckcronk\nsydh5524\nmfuji09\npgmreddy\nwbamberg\nfscholz\nBrettz9\ntjcrowder\nRobg1\nfanerge\naetonsi\nirenesmith\njames-owen\nrwaldron\nPeterDavidCarter\nSheppy\nroanongh\njameshkramer\narai\nMichaelRushton\nMingun\nteoli\nethertank\nziyunfei\njstrimpel\nevilpie\nMgjbot\nMaian\nNickolay\nDria\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 112} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar", "title": "Lexical grammar", "content": "Lexical grammar\nThis page describes JavaScript's lexical grammar. JavaScript source text is just a sequence of characters \u2014 in order for the interpreter to understand it, the string has to be parsed to a more structured representation. The initial step of parsing is called lexical analysis, in which the text gets scanned from left to right and is converted into a sequence of individual, atomic input elements. Some input elements are insignificant to the interpreter, and will be stripped after this step \u2014 they include white space and comments. The others, including identifiers, keywords, literals, and punctuators (mostly operators), will be used for further syntax analysis. Line terminators and multiline comments are also syntactically insignificant, but they guide the process for automatic semicolons insertion to make certain invalid token sequences become valid.\nFormat-control characters\nFormat-control characters have no visual representation but are used to control the interpretation of the text.\n| Code point | Name | Abbreviation | Description |\n|---|---|---|---|\n| U+200C | Zero width non-joiner | | Placed between characters to prevent being connected into ligatures in certain languages (Wikipedia). |\n| U+200D | Zero width joiner | | Placed between characters that would not normally be connected in order to cause the characters to be rendered using their connected form in certain languages (Wikipedia). |\n| U+FEFF | Byte order mark | | Used at the start of the script to mark it as Unicode and to allow detection of the text's encoding and byte order (Wikipedia). |\nIn JavaScript source text, and are treated as identifier parts, while (also called a zero-width no-break space when not at the start of text) is treated as white space.\nWhite space\nWhite space characters improve the readability of source text and separate tokens from each other. These characters are usually unnecessary for the functionality of the code. Minification tools are often used to remove whitespace in order to reduce the amount of data that needs to be transferred.\n| Code point | Name | Abbreviation | Description | Escape sequence |\n|---|---|---|---|---|\n| U+0009 | Character tabulation | | Horizontal tabulation | \\t |\n| U+000B | Line tabulation | | Vertical tabulation | \\v |\n| U+000C | Form feed | | Page breaking control character (Wikipedia). | \\f |\n| U+0020 | Space | | Normal space | |\n| U+00A0 | No-break space | | Normal space, but no point at which a line may break | |\n| U+FEFF | Zero-width no-break space | | When not at the start of a script, the BOM marker is a normal whitespace character. | |\n| Others | Other Unicode space characters | | Characters in the \"Space_Separator\" general category |\nNote: Of those characters with the \"White_Space\" property but are not in the \"Space_Separator\" general category, U+0009, U+000B, and U+000C are still treated as white space in JavaScript; U+0085 NEXT LINE has no special role; others become the set of line terminators.\nNote:\nChanges to the Unicode standard used by the JavaScript engine may affect programs' behavior. For example, ES2016 upgraded the reference Unicode standard from 5.1 to 8.0.0, which caused U+180E MONGOLIAN VOWEL SEPARATOR to be moved from the \"Space_Separator\" category to the \"Format (Cf)\" category, and made it a non-whitespace. Subsequently, the result of \"\\u180E\".trim().length\nchanged from 0\nto 1\n.\nLine terminators\nIn addition to white space characters, line terminator characters are used to improve the readability of the source text. However, in some cases, line terminators can influence the execution of JavaScript code as there are a few places where they are forbidden. Line terminators also affect the process of automatic semicolon insertion.\nOutside the context of lexical grammar, white space and line terminators are often conflated. For example, String.prototype.trim()\nremoves all white space and line terminators from the beginning and end of a string. The \\s\ncharacter class escape in regular expressions matches all white space and line terminators.\nOnly the following Unicode code points are treated as line terminators in ECMAScript, other line breaking characters are treated as white space (for example, Next Line, NEL, U+0085 is considered as white space).\nComments\nComments are used to add hints, notes, suggestions, or warnings to JavaScript code. This can make it easier to read and understand. They can also be used to disable code to prevent it from being executed; this can be a valuable debugging tool.\nJavaScript has two long-standing ways to add comments to code: line comments and block comments. In addition, there's a special hashbang comment syntax.\nLine comments\nThe first way is the //\ncomment; this makes all text following it on the same line into a comment. For example:\nfunction comment() {\n// This is a one line JavaScript comment\nconsole.log(\"Hello world!\");\n}\ncomment();\nBlock comments\nThe second way is the /* */\nstyle, which is much more flexible.\nFor example, you can use it on a single line:\nfunction comment() {\n/* This is a one line JavaScript comment */\nconsole.log(\"Hello world!\");\n}\ncomment();\nYou can also make multiple-line comments, like this:\nfunction comment() {\n/* This comment spans multiple lines. Notice\nthat we don't need to end the comment until we're done. */\nconsole.log(\"Hello world!\");\n}\ncomment();\nYou can also use it in the middle of a line, if you wish, although this can make your code harder to read so it should be used with caution:\nfunction comment(x) {\nconsole.log(\"Hello \" + x /* insert the value of x */ + \" !\");\n}\ncomment(\"world\");\nIn addition, you can use it to disable code to prevent it from running, by wrapping code in a comment, like this:\nfunction comment() {\n/* console.log(\"Hello world!\"); */\n}\ncomment();\nIn this case, the console.log()\ncall is never issued, since it's inside a comment. Any number of lines of code can be disabled this way.\nBlock comments that contain at least one line terminator behave like line terminators in automatic semicolon insertion.\nHashbang comments\nThere's a special third comment syntax, the hashbang comment. A hashbang comment behaves exactly like a single line-only (//\n) comment, except that it begins with #!\nand is only valid at the absolute start of a script or module. Note also that no whitespace of any kind is permitted before the #!\n. The comment consists of all the characters after #!\nup to the end of the first line; only one such comment is permitted.\nHashbang comments in JavaScript resemble shebangs in Unix which provide the path to a specific JavaScript interpreter that you want to use to execute the script. Before the hashbang comment became standardized, it had already been de-facto implemented in non-browser hosts like Node.js, where it was stripped from the source text before being passed to the engine. An example is as follows:\n#!/usr/bin/env node\nconsole.log(\"Hello world\");\nThe JavaScript interpreter will treat it as a normal comment \u2014 it only has semantic meaning to the shell if the script is directly run in a shell.\nWarning: If you want scripts to be runnable directly in a shell environment, encode them in UTF-8 without a BOM. Although a BOM will not cause any problems for code running in a browser \u2014 because it's stripped during UTF-8 decoding, before the source text is analyzed \u2014 a Unix/Linux shell will not recognize the hashbang if it's preceded by a BOM character.\nYou must only use the #!\ncomment style to specify a JavaScript interpreter. In all other cases just use a //\ncomment (or multiline comment).\nIdentifiers\nAn identifier is used to link a value with a name. Identifiers can be used in various places:\nconst decl = 1; // Variable declaration (may also be `let` or `var`)\nfunction fn() {} // Function declaration\nconst obj = { key: \"value\" }; // Object keys\n// Class declaration\nclass C {\n#priv = \"value\"; // Private field\n}\nlbl: console.log(1); // Label\nIn JavaScript, identifiers are commonly made of alphanumeric characters, underscores (_\n), and dollar signs ($\n). Identifiers are not allowed to start with numbers. However, JavaScript identifiers are not only limited to ASCII \u2014 many Unicode code points are allowed as well. Namely:\n- Start characters can be any character in the ID_Start category plus\n_\nand$\n. - After the first character, you can use any character in the ID_Continue category plus U+200C (ZWNJ) and U+200D (ZWJ).\nNote:\nIf, for some reason, you need to parse some JavaScript source yourself, do not assume all identifiers follow the pattern /[A-Za-z_$][\\w$]*/\n(i.e., ASCII-only)! The range of identifiers can be described by the regex /[$_\\p{ID_Start}][$\\p{ID_Continue}]*/u\n(excluding unicode escape sequences).\nIn addition, JavaScript allows using Unicode escape sequences in the form of \\u0000\nor \\u{000000}\nin identifiers, which encode the same string value as the actual Unicode characters. For example, \u4f60\u597d\nand \\u4f60\\u597d\nare the same identifiers:\nconst \u4f60\u597d = \"Hello\";\nconsole.log(\\u4f60\\u597d); // Hello\nNot all places accept the full range of identifiers. Certain syntaxes, such as function declarations, function expressions, and variable declarations require using identifiers names that are not reserved words.\nfunction import() {} // Illegal: import is a reserved word.\nMost notably, private elements and object properties allow reserved words.\nconst obj = { import: \"value\" }; // Legal despite `import` being reserved\nclass C {\n#import = \"value\";\n}\nKeywords\nKeywords are tokens that look like identifiers but have special meanings in JavaScript. For example, the keyword async\nbefore a function declaration indicates that the function is asynchronous.\nSome keywords are reserved, meaning that they cannot be used as an identifier for variable declarations, function declarations, etc. They are often called reserved words. A list of these reserved words is provided below. Not all keywords are reserved \u2014 for example, async\ncan be used as an identifier anywhere. Some keywords are only contextually reserved \u2014 for example, await\nis only reserved within the body of an async function, and let\nis only reserved in strict mode code, or const\nand let\ndeclarations.\nIdentifiers are always compared by string value, so escape sequences are interpreted. For example, this is still a syntax error:\nconst els\\u{65} = 1;\n// `els\\u{65}` encodes the same identifier as `else`\nReserved words\nThese keywords cannot be used as identifiers for variables, functions, classes, etc. anywhere in JavaScript source.\nbreak\ncase\ncatch\nclass\nconst\ncontinue\ndebugger\ndefault\ndelete\ndo\nelse\nexport\nextends\nfalse\nfinally\nfor\nfunction\nif\nimport\nin\ninstanceof\nnew\nnull\nreturn\nsuper\nswitch\nthis\nthrow\ntrue\ntry\ntypeof\nvar\nvoid\nwhile\nwith\nThe following are only reserved when they are found in strict mode code:\nlet\n(also reserved inconst\n,let\n, and class declarations)static\nyield\n(also reserved in generator function bodies)\nThe following are only reserved when they are found in module code or async function bodies:\nFuture reserved words\nThe following are reserved as future keywords by the ECMAScript specification. They have no special functionality at present, but they might at some future time, so they cannot be used as identifiers.\nThese are always reserved:\nenum\nThe following are only reserved when they are found in strict mode code:\nimplements\ninterface\npackage\nprivate\nprotected\npublic\nFuture reserved words in older standards\nThe following are reserved as future keywords by older ECMAScript specifications (ECMAScript 1 till 3).\nabstract\nboolean\nbyte\nchar\ndouble\nfinal\nfloat\ngoto\nint\nlong\nnative\nshort\nsynchronized\nthrows\ntransient\nvolatile\nIdentifiers with special meanings\nA few identifiers have a special meaning in some contexts without being reserved words of any kind. They include:\narguments\n(not a keyword, but cannot be declared as identifier in strict mode)as\n(import * as ns from \"mod\"\n)async\neval\n(not a keyword, but cannot be declared as identifier in strict mode)from\n(import x from \"mod\"\n)get\nof\nset\nLiterals\nNote: This section discusses literals that are atomic tokens. Object literals and array literals are expressions that consist of a series of tokens.\nNull literal\nSee also null\nfor more information.\nnull\nBoolean literal\nSee also boolean type for more information.\ntrue\nfalse\nNumeric literals\nThe Number and BigInt types use numeric literals.\nDecimal\n1234567890\n42\nDecimal literals can start with a zero (0\n) followed by another decimal digit, but if all digits after the leading 0\nare smaller than 8, the number is interpreted as an octal number. This is considered a legacy syntax, and number literals prefixed with 0\n, whether interpreted as octal or decimal, cause a syntax error in strict mode \u2014 so, use the 0o\nprefix instead.\n0888 // 888 parsed as decimal\n0777 // parsed as octal, 511 in decimal\nExponential\nThe decimal exponential literal is specified by the following format: beN\n; where b\nis a base number (integer or floating), followed by an E\nor e\ncharacter (which serves as separator or exponent indicator) and N\n, which is exponent or power number \u2013 a signed integer.\n0e-5 // 0\n0e+5 // 0\n5e1 // 50\n175e-2 // 1.75\n1e3 // 1000\n1e-3 // 0.001\n1E3 // 1000\nBinary\nBinary number syntax uses a leading zero followed by a lowercase or uppercase Latin letter \"B\" (0b\nor 0B\n). Any character after the 0b\nthat is not 0 or 1 will terminate the literal sequence.\n0b10000000000000000000000000000000 // 2147483648\n0b01111111100000000000000000000000 // 2139095040\n0B00000000011111111111111111111111 // 8388607\nOctal\nOctal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter \"O\" (0o\nor 0O)\n. Any character after the 0o\nthat is outside the range (01234567) will terminate the literal sequence.\n0O755 // 493\n0o644 // 420\nHexadecimal\nHexadecimal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter \"X\" (0x\nor 0X\n). Any character after the 0x\nthat is outside the range (0123456789ABCDEF) will terminate the literal sequence.\n0xFFFFFFFFFFFFF // 4503599627370495\n0xabcdef123456 // 188900967593046\n0XA // 10\nBigInt literal\nThe BigInt type is a numeric primitive in JavaScript that can represent integers with arbitrary precision. BigInt literals are created by appending n\nto the end of an integer.\n123456789123456789n // 123456789123456789\n0o777777777777n // 68719476735\n0x123456789ABCDEFn // 81985529216486895\n0b11101001010101010101n // 955733\nBigInt literals cannot start with 0\nto avoid confusion with legacy octal literals.\n0755n; // SyntaxError: invalid BigInt syntax\nFor octal BigInt\nnumbers, always use zero followed by the letter \"o\" (uppercase or lowercase):\n0o755n;\nFor more information about BigInt\n, see also JavaScript data structures.\nNumeric separators\nTo improve readability for numeric literals, underscores (_\n, U+005F\n) can be used as separators:\n1_000_000_000_000\n1_050.95\n0b1010_0001_1000_0101\n0o2_2_5_6\n0xA0_B0_C0\n1_000_000_000_000_000_000_000n\nNote these limitations:\n// More than one underscore in a row is not allowed\n100__000; // SyntaxError\n// Not allowed at the end of numeric literals\n100_; // SyntaxError\n// Can not be used after leading 0\n0_1; // SyntaxError\nString literals\nA string literal is zero or more Unicode code points enclosed in single or double quotes. Unicode code points may also be represented by an escape sequence. All code points may appear literally in a string literal except for these code points:\n- U+005C \\ (backslash)\n- U+000D \n- U+000A \n- The same kind of quote that begins the string literal\nAny code points may appear in the form of an escape sequence. String literals evaluate to ECMAScript String values. When generating these String values Unicode code points are UTF-16 encoded.\n'foo'\n\"bar\"\nThe following subsections describe various escape sequences (\\\nfollowed by one or more characters) available in string literals. Any escape sequence not listed below becomes an \"identity escape\" that becomes the code point itself. For example, \\z\nis the same as z\n. There's a deprecated octal escape sequence syntax described in the Deprecated and obsolete features page. Many of these escape sequences are also valid in regular expressions \u2014 see Character escape.\nEscape sequences\nSpecial characters can be encoded using escape sequences:\n| Escape sequence | Unicode code point |\n|---|---|\n\\0 |\nnull character (U+0000 NULL) |\n\\' |\nsingle quote (U+0027 APOSTROPHE) |\n\\\" |\ndouble quote (U+0022 QUOTATION MARK) |\n\\\\ |\nbackslash (U+005C REVERSE SOLIDUS) |\n\\n |\nnewline (U+000A LINE FEED; LF) |\n\\r |\ncarriage return (U+000D CARRIAGE RETURN; CR) |\n\\v |\nvertical tab (U+000B LINE TABULATION) |\n\\t |\ntab (U+0009 CHARACTER TABULATION) |\n\\b |\nbackspace (U+0008 BACKSPACE) |\n\\f |\nform feed (U+000C FORM FEED) |\n\\ followed by a line terminator |\nempty string |\nThe last escape sequence, \\\nfollowed by a line terminator, is useful for splitting a string literal across multiple lines without changing its meaning.\nconst longString =\n\"This is a very long string which needs \\\nto wrap across multiple lines because \\\notherwise my code is unreadable.\";\nMake sure there is no space or any other character after the backslash (except for a line break), otherwise it will not work. If the next line is indented, the extra spaces will also be present in the string's value.\nYou can also use the +\noperator to append multiple strings together, like this:\nconst longString =\n\"This is a very long string which needs \" +\n\"to wrap across multiple lines because \" +\n\"otherwise my code is unreadable.\";\nBoth of the above methods result in identical strings.\nHexadecimal escape sequences\nHexadecimal escape sequences consist of \\x\nfollowed by exactly two hexadecimal digits representing a code unit or code point in the range 0x0000 to 0x00FF.\n\"\\xA9\"; // \"\u00a9\"\nUnicode escape sequences\nA Unicode escape sequence consists of exactly four hexadecimal digits following \\u\n. It represents a code unit in the UTF-16 encoding. For code points U+0000 to U+FFFF, the code unit is equal to the code point. Code points U+10000 to U+10FFFF require two escape sequences representing the two code units (a surrogate pair) used to encode the character; the surrogate pair is distinct from the code point.\nSee also String.fromCharCode()\nand String.prototype.charCodeAt()\n.\n\"\\u00A9\"; // \"\u00a9\" (U+A9)\nUnicode code point escapes\nA Unicode code point escape consists of \\u{\n, followed by a code point in hexadecimal base, followed by }\n. The value of the hexadecimal digits must be in the range 0 and 0x10FFFF inclusive. Code points in the range U+10000 to U+10FFFF do not need to be represented as a surrogate pair.\nSee also String.fromCodePoint()\nand String.prototype.codePointAt()\n.\n\"\\u{2F804}\"; // CJK COMPATIBILITY IDEOGRAPH-2F804 (U+2F804)\n// the same character represented as a surrogate pair\n\"\\uD87E\\uDC04\";\nRegular expression literals\nRegular expression literals are enclosed by two forward slashes (/\n). The lexer consumes all characters up to the next unescaped forward slash or the end of the line, unless the forward slash appears within a character class ([]\n). Some characters (namely, those that are identifier parts) can appear after the closing slash, denoting flags.\nThe lexical grammar is very lenient: not all regular expression literals that get identified as one token are valid regular expressions.\nSee also RegExp\nfor more information.\n/ab+c/g;\n/[/]/;\nA regular expression literal cannot start with two forward slashes (//\n), because that would be a line comment. To specify an empty regular expression, use /(?:)/\n.\nTemplate literals\nOne template literal consists of several tokens: `xxx${\n(template head), }xxx${\n(template middle), and }xxx`\n(template tail) are individual tokens, while any expression may come between them.\nSee also template literals for more information.\n`string text`;\n`string text line 1\nstring text line 2`;\n`string text ${expression} string text`;\ntag`string text ${expression} string text`;\nAutomatic semicolon insertion\nSome JavaScript statements' syntax definitions require semicolons (;\n) at the end. They include:\nvar\n,let\n,const\n,using\n,await using\n- Expression statements\ndo...while\ncontinue\n,break\n,return\n,throw\ndebugger\n- Class field declarations (public or private)\nimport\n,export\nHowever, to make the language more approachable and convenient, JavaScript is able to automatically insert semicolons when consuming the token stream, so that some invalid token sequences can be \"fixed\" to valid syntax. This step happens after the program text has been parsed to tokens according to the lexical grammar. There are three cases when semicolons are automatically inserted:\n1. When a token not allowed by the grammar is encountered, and it's separated from the previous token by at least one line terminator (including a block comment that includes at least one line terminator), or the token is \"}\", then a semicolon is inserted before the token.\n{ 1\n2 } 3\n// is transformed by ASI into:\n{ 1\n;2 ;} 3;\n// Which is valid grammar encoding three statements,\n// each consisting of a number literal\nThe ending \")\" of do...while\nis taken care of as a special case by this rule as well.\ndo {\n// \u2026\n} while (condition) /* ; */ // ASI here\nconst a = 1\nHowever, semicolons are not inserted if the semicolon would then become the separator in the for\nstatement's head.\nfor (\nlet a = 1 // No ASI here\na < 10 // No ASI here\na++\n) {}\nSemicolons are also never inserted as empty statements. For example, in the code below, if a semicolon is inserted after \")\", then the code would be valid, with an empty statement as the if\nbody and the const\ndeclaration being a separate statement. However, because automatically inserted semicolons cannot become empty statements, this causes a declaration to become the body of the if\nstatement, which is not valid.\nif (Math.random() > 0.5)\nconst x = 1 // SyntaxError: Unexpected token 'const'\n2. When the end of the input stream of tokens is reached, and the parser is unable to parse the single input stream as a complete program, a semicolon is inserted at the end.\nconst a = 1 /* ; */ // ASI here\nThis rule is a complement to the previous rule, specifically for the case where there's no \"offending token\" but the end of input stream.\n3. When the grammar forbids line terminators in some place but a line terminator is found, a semicolon is inserted. These places include:\nexpr ++\n,expr --\ncontinue lbl\nbreak lbl\nreturn expr\nthrow expr\nyield expr\nyield * expr\n(param) => {}\nasync function\n,async prop()\n,async function*\n,async *prop()\n,async (param) => {}\nusing id\n,await using id\nHere ++\nis not treated as a postfix operator applying to variable b\n, because a line terminator occurs between b\nand ++\n.\na = b\n++c\n// is transformed by ASI into\na = b;\n++c;\nHere, the return\nstatement returns undefined\n, and the a + b\nbecomes an unreachable statement.\nreturn\na + b\n// is transformed by ASI into\nreturn;\na + b;\nNote that ASI would only be triggered if a line break separates tokens that would otherwise produce invalid syntax. If the next token can be parsed as part of a valid structure, semicolons would not be inserted. For example:\nconst a = 1\n(1).toString()\nconst b = 1\n[1, 2, 3].forEach(console.log)\nBecause ()\ncan be seen as a function call, it would usually not trigger ASI. Similarly, []\nmay be a member access. The code above is equivalent to:\nconst a = 1(1).toString();\nconst b = 1[1, 2, 3].forEach(console.log);\nThis happens to be valid syntax. 1[1, 2, 3]\nis a property accessor with a comma-joined expression. Therefore, you would get errors like \"1 is not a function\" and \"Cannot read properties of undefined (reading 'forEach')\" when running the code.\nWithin classes, class fields and generator methods can be a pitfall as well.\nclass A {\na = 1\n*gen() {}\n}\nIt is seen as:\nclass A {\na = 1 * gen() {}\n}\nAnd therefore will be a syntax error around {\n.\nThere are the following rules-of-thumb for dealing with ASI, if you want to enforce semicolon-less style:\n-\nWrite postfix\n++\nand--\non the same line as their operands.jsconst a = b ++ console.log(a) // ReferenceError: Invalid left-hand side expression in prefix operation\njsconst a = b++ console.log(a)\n-\nThe expressions after\nreturn\n,throw\n, oryield\nshould be on the same line as the keyword.jsfunction foo() { return 1 + 1 // Returns undefined; 1 + 1 is ignored }\njsfunction foo() { return 1 + 1 } function foo() { return ( 1 + 1 ) }\n-\nSimilarly, the label identifier after\nbreak\norcontinue\nshould be on the same line as the keyword.jsouterBlock: { innerBlock: { break outerBlock // SyntaxError: Illegal break statement } }\njsouterBlock: { innerBlock: { break outerBlock } }\n-\nThe\n=>\nof an arrow function should be on the same line as the end of its parameters.jsconst foo = (a, b) => a + b\njsconst foo = (a, b) => a + b\n-\nThe\nasync\nof async functions, methods, etc. cannot be directly followed by a line terminator.jsasync function foo() {}\njsasync function foo() {}\n-\nThe\nusing\nkeyword inusing\nandawait using\nstatements should be on the same line as the first identifier it declares.jsusing resource = acquireResource()\njsusing resource = acquireResource()\n-\nIf a line starts with one of\n(\n,[\n,`\n,+\n,-\n,/\n(as in regex literals), prefix it with a semicolon, or end the previous line with a semicolon.js// The () may be merged with the previous line as a function call (() => { // \u2026 })() // The [ may be merged with the previous line as a property access [1, 2, 3].forEach(console.log) // The ` may be merged with the previous line as a tagged template literal `string text ${data}`.match(pattern).forEach(console.log) // The + may be merged with the previous line as a binary + expression +a.toString() // The - may be merged with the previous line as a binary - expression -a.toString() // The / may be merged with the previous line as a division expression /pattern/.exec(str).forEach(console.log)\njs;(() => { // \u2026 })() ;[1, 2, 3].forEach(console.log) ;`string text ${data}`.match(pattern).forEach(console.log) ;+a.toString() ;-a.toString() ;/pattern/.exec(str).forEach(console.log)\n-\nClass fields should preferably always be ended with semicolons \u2014 in addition to the previous rule (which includes a field declaration followed by a computed property, since the latter starts with\n[\n), semicolons are also required between a field declaration and a generator method.jsclass A { a = 1 [b] = 2 *gen() {} // Seen as a = 1[b] = 2 * gen() {} }\njsclass A { a = 1; [b] = 2; *gen() {} }\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification |\nBrowser compatibility\nSee also\n- Grammar and types guide\n- Micro-feature from ES6, now in Firefox Aurora and Nightly: binary and octal numbers by Jeff Walden (2013)\n- JavaScript character escape sequences by Mathias Bynens (2011)", "code_snippets": ["function comment() {\n // This is a one line JavaScript comment\n console.log(\"Hello world!\");\n}\ncomment();\n", "function comment() {\n /* This is a one line JavaScript comment */\n console.log(\"Hello world!\");\n}\ncomment();\n", "function comment() {\n /* This comment spans multiple lines. Notice\n that we don't need to end the comment until we're done. */\n console.log(\"Hello world!\");\n}\ncomment();\n", "function comment(x) {\n console.log(\"Hello \" + x /* insert the value of x */ + \" !\");\n}\ncomment(\"world\");\n", "function comment() {\n /* console.log(\"Hello world!\"); */\n}\ncomment();\n", "#!/usr/bin/env node\n\nconsole.log(\"Hello world\");\n", "const decl = 1; // Variable declaration (may also be `let` or `var`)\nfunction fn() {} // Function declaration\nconst obj = { key: \"value\" }; // Object keys\n// Class declaration\nclass C {\n #priv = \"value\"; // Private field\n}\nlbl: console.log(1); // Label\n", "const \u4f60\u597d = \"Hello\";\nconsole.log(\\u4f60\\u597d); // Hello\n", "function import() {} // Illegal: import is a reserved word.\n", "const obj = { import: \"value\" }; // Legal despite `import` being reserved\nclass C {\n #import = \"value\";\n}\n", "const els\\u{65} = 1;\n// `els\\u{65}` encodes the same identifier as `else`\n", "null\n", "true\nfalse\n", "1234567890\n42\n", "0888 // 888 parsed as decimal\n0777 // parsed as octal, 511 in decimal\n", "0e-5 // 0\n0e+5 // 0\n5e1 // 50\n175e-2 // 1.75\n1e3 // 1000\n1e-3 // 0.001\n1E3 // 1000\n", "0b10000000000000000000000000000000 // 2147483648\n0b01111111100000000000000000000000 // 2139095040\n0B00000000011111111111111111111111 // 8388607\n", "0O755 // 493\n0o644 // 420\n", "0xFFFFFFFFFFFFF // 4503599627370495\n0xabcdef123456 // 188900967593046\n0XA // 10\n", "123456789123456789n // 123456789123456789\n0o777777777777n // 68719476735\n0x123456789ABCDEFn // 81985529216486895\n0b11101001010101010101n // 955733\n", "0755n; // SyntaxError: invalid BigInt syntax\n", "0o755n;\n", "1_000_000_000_000\n1_050.95\n0b1010_0001_1000_0101\n0o2_2_5_6\n0xA0_B0_C0\n1_000_000_000_000_000_000_000n\n", "// More than one underscore in a row is not allowed\n100__000; // SyntaxError\n\n// Not allowed at the end of numeric literals\n100_; // SyntaxError\n\n// Can not be used after leading 0\n0_1; // SyntaxError\n", "'foo'\n\"bar\"\n", "const longString =\n \"This is a very long string which needs \\\nto wrap across multiple lines because \\\notherwise my code is unreadable.\";\n", "const longString =\n \"This is a very long string which needs \" +\n \"to wrap across multiple lines because \" +\n \"otherwise my code is unreadable.\";\n", "\"\\xA9\"; // \"\u00a9\"\n", "\"\\u00A9\"; // \"\u00a9\" (U+A9)\n", "\"\\u{2F804}\"; // CJK COMPATIBILITY IDEOGRAPH-2F804 (U+2F804)\n\n// the same character represented as a surrogate pair\n\"\\uD87E\\uDC04\";\n", "/ab+c/g;\n/[/]/;\n", "`string text`;\n\n`string text line 1\n string text line 2`;\n\n`string text ${expression} string text`;\n\ntag`string text ${expression} string text`;\n", "{ 1\n2 } 3\n\n// is transformed by ASI into:\n\n{ 1\n;2 ;} 3;\n\n// Which is valid grammar encoding three statements,\n// each consisting of a number literal\n", "do {\n // \u2026\n} while (condition) /* ; */ // ASI here\nconst a = 1\n", "for (\n let a = 1 // No ASI here\n a < 10 // No ASI here\n a++\n) {}\n", "if (Math.random() > 0.5)\nconst x = 1 // SyntaxError: Unexpected token 'const'\n", "const a = 1 /* ; */ // ASI here\n", "a = b\n++c\n\n// is transformed by ASI into\n\na = b;\n++c;\n", "return\na + b\n\n// is transformed by ASI into\n\nreturn;\na + b;\n", "const a = 1\n(1).toString()\n\nconst b = 1\n[1, 2, 3].forEach(console.log)\n", "const a = 1(1).toString();\n\nconst b = 1[1, 2, 3].forEach(console.log);\n", "class A {\n a = 1\n *gen() {}\n}\n", "class A {\n a = 1 * gen() {}\n}\n", "const a = b\n++\nconsole.log(a) // ReferenceError: Invalid left-hand side expression in prefix operation\n", "const a = b++\nconsole.log(a)\n", "function foo() {\n return\n 1 + 1 // Returns undefined; 1 + 1 is ignored\n}\n", "function foo() {\n return 1 + 1\n}\n\nfunction foo() {\n return (\n 1 + 1\n )\n}\n", "outerBlock: {\n innerBlock: {\n break\n outerBlock // SyntaxError: Illegal break statement\n }\n}\n", "outerBlock: {\n innerBlock: {\n break outerBlock\n }\n}\n", "const foo = (a, b)\n => a + b\n", "const foo = (a, b) =>\n a + b\n", "async\nfunction foo() {}\n", "async function\nfoo() {}\n", "using\nresource = acquireResource()\n", "using resource\n = acquireResource()\n", "// The () may be merged with the previous line as a function call\n(() => {\n // \u2026\n})()\n\n// The [ may be merged with the previous line as a property access\n[1, 2, 3].forEach(console.log)\n\n// The ` may be merged with the previous line as a tagged template literal\n`string text ${data}`.match(pattern).forEach(console.log)\n\n// The + may be merged with the previous line as a binary + expression\n+a.toString()\n\n// The - may be merged with the previous line as a binary - expression\n-a.toString()\n\n// The / may be merged with the previous line as a division expression\n/pattern/.exec(str).forEach(console.log)\n", ";(() => {\n // \u2026\n})()\n;[1, 2, 3].forEach(console.log)\n;`string text ${data}`.match(pattern).forEach(console.log)\n;+a.toString()\n;-a.toString()\n;/pattern/.exec(str).forEach(console.log)\n", "class A {\n a = 1\n [b] = 2\n *gen() {} // Seen as a = 1[b] = 2 * gen() {}\n}\n", "class A {\n a = 1;\n [b] = 2;\n *gen() {}\n}\n"], "language": "JavaScript", "source": "mdn", "token_count": 7990} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols", "title": "Iteration protocols", "content": "Iteration protocols\nIteration protocols aren't new built-ins or syntax, but protocols. These protocols can be implemented by any object by following some conventions.\nThere are two protocols: The iterable protocol and the iterator protocol.\nThe iterable protocol\nThe iterable protocol allows JavaScript objects to define or customize their iteration behavior, such as what values are looped over in a for...of\nconstruct. Some built-in types are built-in iterables with a default iteration behavior, such as Array\nor Map\n, while other types (such as Object\n) are not.\nIn order to be iterable, an object must implement the [Symbol.iterator]()\nmethod, meaning that the object (or one of the objects up its prototype chain) must have a property with a [Symbol.iterator]\nkey which is available via constant Symbol.iterator\n:\n[Symbol.iterator]()\n-\nA zero-argument function that returns an object, conforming to the iterator protocol.\nWhenever an object needs to be iterated (such as at the beginning of a for...of\nloop), its [Symbol.iterator]()\nmethod is called with no arguments, and the returned iterator is used to obtain the values to be iterated.\nNote that when this zero-argument function is called, it is invoked as a method on the iterable object. Therefore inside of the function, the this\nkeyword can be used to access the properties of the iterable object, to decide what to provide during the iteration.\nThis function can be an ordinary function, or it can be a generator function, so that when invoked, an iterator object is returned. Inside of this generator function, each entry can be provided by using yield\n.\nThe iterator protocol\nThe iterator protocol defines a standard way to produce a sequence of values (either finite or infinite), and potentially a return value when all values have been generated.\nAn object is an iterator when it implements a next()\nmethod with the following semantics:\nnext()\n-\nA function that accepts zero or one argument and returns an object conforming to the\nIteratorResult\ninterface (see below). If a non-object value gets returned (such asfalse\norundefined\n) when a built-in language feature (such asfor...of\n) is using the iterator, aTypeError\n(\"iterator.next() returned a non-object value\"\n) will be thrown.\nAll iterator protocol methods (next()\n, return()\n, and throw()\n) are expected to return an object implementing the IteratorResult\ninterface. It must have the following properties:\ndone\nOptional-\nA boolean that's\nfalse\nif the iterator was able to produce the next value in the sequence. (This is equivalent to not specifying thedone\nproperty altogether.)Has the value\ntrue\nif the iterator has completed its sequence. In this case,value\noptionally specifies the return value of the iterator. value\nOptional-\nAny JavaScript value returned by the iterator. Can be omitted when\ndone\nistrue\n.\nIn practice, neither property is strictly required; if an object without either property is returned, it's effectively equivalent to { done: false, value: undefined }\n.\nIf an iterator returns a result with done: true\n, any subsequent calls to next()\nare expected to return done: true\nas well, although this is not enforced on the language level.\nThe next\nmethod can receive a value which will be made available to the method body. No built-in language feature will pass any value. The value passed to the next\nmethod of generators will become the value of the corresponding yield\nexpression.\nOptionally, the iterator can also implement the return(value)\nand throw(exception)\nmethods, which, when called, tells the iterator that the caller is done with iterating it and can perform any necessary cleanup (such as closing database connection).\nreturn(value)\nOptional-\nA function that accepts zero or one argument and returns an object conforming to the\nIteratorResult\ninterface, typically withvalue\nequal to thevalue\npassed in anddone\nequal totrue\n. Calling this method tells the iterator that the caller does not intend to make any morenext()\ncalls and can perform any cleanup actions. When built-in language features callreturn()\nfor cleanup,value\nis alwaysundefined\n. throw(exception)\nOptional-\nA function that accepts zero or one argument and returns an object conforming to the\nIteratorResult\ninterface, typically withdone\nequal totrue\n. Calling this method tells the iterator that the caller detects an error condition, andexception\nis typically anError\ninstance. No built-in language feature callsthrow()\nfor cleanup purposes \u2014 it's a special feature of generators for the symmetry ofreturn\n/throw\n.\nNote:\nIt is not possible to know reflectively (i.e., without actually calling next()\nand validating the returned result) whether a particular object implements the iterator protocol.\nIt is very easy to make an iterator also iterable: just implement a [Symbol.iterator]()\nmethod that returns this\n.\n// Satisfies both the Iterator Protocol and Iterable\nconst myIterator = {\nnext() {\n// \u2026\n},\n[Symbol.iterator]() {\nreturn this;\n},\n};\nSuch object is called an iterable iterator. Doing so allows an iterator to be consumed by the various syntaxes expecting iterables \u2014 therefore, it is seldom useful to implement the Iterator Protocol without also implementing Iterable. (In fact, almost all syntaxes and APIs expect iterables, not iterators.) The generator object is an example:\nconst generatorObject = (function* () {\nyield 1;\nyield 2;\nyield 3;\n})();\nconsole.log(typeof generatorObject.next);\n// \"function\" \u2014 it has a next method (which returns the right result), so it's an iterator\nconsole.log(typeof generatorObject[Symbol.iterator]);\n// \"function\" \u2014 it has a [Symbol.iterator] method (which returns the right iterator), so it's an iterable\nconsole.log(generatorObject[Symbol.iterator]() === generatorObject);\n// true \u2014 its [Symbol.iterator] method returns itself (an iterator), so it's an iterable iterator\nAll built-in iterators inherit from Iterator.prototype\n, which implements the [Symbol.iterator]()\nmethod as returning this\n, so that built-in iterators are also iterable.\nHowever, when possible, it's better for iterable[Symbol.iterator]()\nto return different iterators that always start from the beginning, like Set.prototype[Symbol.iterator]()\ndoes.\nThe async iterator and async iterable protocols\nThere are another pair of protocols used for async iteration, named async iterator and async iterable protocols. They have very similar interfaces compared to the iterable and iterator protocols, except that each return value from the calls to the iterator methods is wrapped in a promise.\nAn object implements the async iterable protocol when it implements the following methods:\n[Symbol.asyncIterator]()\n-\nA zero-argument function that returns an object, conforming to the async iterator protocol.\nAn object implements the async iterator protocol when it implements the following methods:\nnext()\n-\nA function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the\nIteratorResult\ninterface, and the properties have the same semantics as those of the sync iterator's. return(value)\nOptional-\nA function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the\nIteratorResult\ninterface, and the properties have the same semantics as those of the sync iterator's. throw(exception)\nOptional-\nA function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the\nIteratorResult\ninterface, and the properties have the same semantics as those of the sync iterator's.\nInteractions between the language and iteration protocols\nThe language specifies APIs that either produce or consume iterables and iterators.\nBuilt-in iterables\nString\n, Array\n, TypedArray\n, Map\n, Set\n, and Segments\n(returned by Intl.Segmenter.prototype.segment()\n) are all built-in iterables, because each of their prototype\nobjects implements a [Symbol.iterator]()\nmethod. In addition, the arguments\nobject and some DOM collection types such as NodeList\nare also iterables.\nThere is no object in the core JavaScript language that is async iterable. Some web APIs, such as ReadableStream\n, have the Symbol.asyncIterator\nmethod set by default.\nGenerator functions return generator objects, which are iterable iterators. Async generator functions return async generator objects, which are async iterable iterators.\nThe iterators returned from built-in iterables actually all inherit from a common class Iterator\n, which implements the aforementioned [Symbol.iterator]() { return this; }\nmethod, making them all iterable iterators. The Iterator\nclass also provides additional helper methods in addition to the next()\nmethod required by the iterator protocol. You can inspect an iterator's prototype chain by logging it in a graphical console.\nconsole.log([][Symbol.iterator]()); Array Iterator {} [[Prototype]]: Array Iterator ==> This is the prototype shared by all array iterators next: \u0192 next() Symbol(Symbol.toStringTag): \"Array Iterator\" [[Prototype]]: Object ==> This is the prototype shared by all built-in iterators Symbol(Symbol.iterator): \u0192 [Symbol.iterator]() [[Prototype]]: Object ==> This is Object.prototype\nBuilt-in APIs accepting iterables\nThere are many APIs that accept iterables. Some examples include:\nMap()\nWeakMap()\nSet()\nWeakSet()\nPromise.all()\nPromise.allSettled()\nPromise.race()\nPromise.any()\nArray.from()\nObject.groupBy()\nMap.groupBy()\nconst myObj = {};\nnew WeakSet(\n(function* () {\nyield {};\nyield myObj;\nyield {};\n})(),\n).has(myObj); // true\nSyntaxes expecting iterables\nSome statements and expressions expect iterables, for example the for...of\nloops, array and parameter spreading, yield*\n, and array destructuring:\nfor (const value of [\"a\", \"b\", \"c\"]) {\nconsole.log(value);\n}\n// \"a\"\n// \"b\"\n// \"c\"\nconsole.log([...\"abc\"]); // [\"a\", \"b\", \"c\"]\nfunction* gen() {\nyield* [\"a\", \"b\", \"c\"];\n}\nconsole.log(gen().next()); // { value: \"a\", done: false }\n[a, b, c] = new Set([\"a\", \"b\", \"c\"]);\nconsole.log(a); // \"a\"\nWhen built-in syntaxes are iterating an iterator, and the last result's done\nis false\n(i.e., the iterator is able to produce more values) but no more values are needed, the return\nmethod will get called if present. This can happen, for example, if a break\nor return\nis encountered in a for...of\nloop, or if all identifiers are already bound in an array destructuring.\nconst obj = {\n[Symbol.iterator]() {\nlet i = 0;\nreturn {\nnext() {\ni++;\nconsole.log(\"Returning\", i);\nif (i === 3) return { done: true, value: i };\nreturn { done: false, value: i };\n},\nreturn() {\nconsole.log(\"Closing\");\nreturn { done: true };\n},\n};\n},\n};\nconst [a] = obj;\n// Returning 1\n// Closing\nconst [b, c, d] = obj;\n// Returning 1\n// Returning 2\n// Returning 3\n// Already reached the end (the last call returned `done: true`),\n// so `return` is not called\nconsole.log([b, c, d]); // [1, 2, undefined]; the value associated with `done: true` is not reachable\nfor (const b of obj) {\nbreak;\n}\n// Returning 1\n// Closing\nThe for await...of\nloop and yield*\nin async generator functions (but not sync generator functions) are the only ways to interact with async iterables. Using for...of\n, array spreading, etc. on an async iterable that's not also a sync iterable (i.e., it has [Symbol.asyncIterator]()\nbut no [Symbol.iterator]()\n) will throw a TypeError: x is not iterable.\nError handling\nBecause iteration involves transferring control back and forth between the iterator and the consumer, error handling happens in both ways: how the consumer handles errors thrown by the iterator, and how the iterator handles errors thrown by the consumer. When you are using one of the built-in ways of iteration, the language may also throw errors because the iterable breaks certain invariants. We will describe how built-in syntaxes generate and handle errors, which can be used as a guideline for your own code if you are manually stepping the iterator.\nNon-well-formed iterables\nErrors may happen when acquiring the iterator from the iterable. The language invariant enforced here is that the iterable must produce a valid iterator:\n- It has a callable\n[Symbol.iterator]()\nmethod. - The\n[Symbol.iterator]()\nmethod returns an object. - The object returned by\n[Symbol.iterator]()\nhas a callablenext()\nmethod.\nWhen using built-in syntax to initiate iteration on a non-well-formed iterable, a TypeError is thrown.\nconst nonWellFormedIterable = { [Symbol.iterator]: 1 };\n[...nonWellFormedIterable]; // TypeError: nonWellFormedIterable is not iterable\nnonWellFormedIterable[Symbol.iterator] = () => 1;\n[...nonWellFormedIterable]; // TypeError: [Symbol.iterator]() returned a non-object value\nnonWellFormedIterable[Symbol.iterator] = () => ({});\n[...nonWellFormedIterable]; // TypeError: nonWellFormedIterable[Symbol.iterator]().next is not a function\nFor async iterables, if its [Symbol.asyncIterator]()\nproperty has value undefined\nor null\n, JavaScript falls back to using the [Symbol.iterator]\nproperty instead (and wraps the resulting iterator into an async iterator by forwarding the methods). Otherwise, the [Symbol.asyncIterator]\nproperty must conform to the above invariants too.\nThis type of errors can be prevented by first validating the iterable before attempting to iterate it. However, it's fairly rare because usually you know the type of the object you are iterating over. If you are receiving this iterable from some other code, you should just let the error propagate to the caller so they know an invalid input was provided.\nErrors during iteration\nMost errors happen when stepping the iterator (calling next()\n). The language invariant enforced here is that the next()\nmethod must return an object (for async iterators, an object after awaiting). Otherwise, a TypeError is thrown.\nIf the invariant is broken or the next()\nmethod throws an error (for async iterators, it may also return a rejected promise), the error is propagated to the caller. For built-in syntaxes, the iteration in progress is aborted without retrying or cleanup (with the assumption that if the next()\nmethod threw the error, then it has cleaned up already). If you are manually calling next()\n, you may catch the error and retry calling next()\n, but in general you should assume the iterator is already closed.\nIf the caller decides to exit iteration for any reason other than the errors in the previous paragraph, such as when it enters an error state in its own code (for example, while handling an invalid value produced by the iterator), it should call the return()\nmethod on the iterator, if one exists. This allows the iterator to perform any cleanup. The return()\nmethod is only called for premature exits\u2014if next()\nreturns done: true\n, the return()\nmethod is not called, with the assumption that the iterator has already cleaned up.\nThe return()\nmethod might be invalid too! The language also enforces that the return()\nmethod must return an object and throws a TypeError otherwise. If the return()\nmethod throws an error, the error is propagated to the caller. However, if the return()\nmethod is called because the caller encountered an error in its own code, then this error overrides the error thrown by the return()\nmethod.\nUsually, the caller implements error handling like this:\ntry {\nfor (const value of iterable) {\n// \u2026\n}\n} catch (e) {\n// Handle the error\n}\nThe catch\nwill be able to catch errors thrown when iterable\nis not a valid iterable, when next()\nthrows an error, when return()\nthrows an error (if the for\nloop exits early), and when the for\nloop body throws an error.\nMost iterators are implemented with generator functions, so we will demonstrate how generator functions typically handle errors:\nfunction* gen() {\ntry {\nyield doSomething();\nyield doSomethingElse();\n} finally {\ncleanup();\n}\n}\nThe lack of catch\nhere causes errors thrown by doSomething()\nor doSomethingElse()\nto propagate to the caller of gen\n. If these errors are caught within the generator function (which is equally advisable), the generator function can decide to continue yielding values or to exit early. However, the finally\nblock is necessary for generators that keep open resources. The finally\nblock is guaranteed to run, either when the last next()\nis called or when return()\nis called.\nForwarding errors\nSome built-in syntaxes wrap an iterator into another iterator. They include the iterator produced by Iterator.from()\n, iterator helper methods (map()\n, filter()\n, take()\n, drop()\n, and flatMap()\n), yield*\n, and a hidden wrapper when you use async iteration (for await...of\n, Array.fromAsync\n) on sync iterators. The wrapped iterator is then responsible for forwarding errors between the inner iterator and the caller.\n- All wrapper iterators directly forward the\nnext()\nmethod of the inner iterator, including its return value and thrown errors. - Wrapper iterators generally directly forward the\nreturn()\nmethod of the inner iterator. If thereturn()\nmethod doesn't exist on the inner iterator, it returns{ done: true, value: undefined }\ninstead. In the case of iterator helpers: if the iterator helper'snext()\nmethod has not been called, after trying to callreturn()\non the inner iterator, the current iterator always returns{ done: true, value: undefined }\n. This is consistent with generator functions where execution hasn't entered theyield*\nexpression yet. yield*\nis the only built-in syntax that forwards thethrow()\nmethod of the inner iterator. For information on howyield*\nforwards thereturn()\nandthrow()\nmethods, see its own reference.\nExamples\nUser-defined iterables\nYou can make your own iterables like this:\nconst myIterable = {\n*[Symbol.iterator]() {\nyield 1;\nyield 2;\nyield 3;\n},\n};\nconsole.log([...myIterable]); // [1, 2, 3]\nBasic iterator\nIterators are stateful by nature. If you don't define it as a generator function (as the example above shows), you would likely want to encapsulate the state in a closure.\nfunction makeIterator(array) {\nlet nextIndex = 0;\nreturn {\nnext() {\nreturn nextIndex < array.length\n? {\nvalue: array[nextIndex++],\ndone: false,\n}\n: {\ndone: true,\n};\n},\n};\n}\nconst it = makeIterator([\"yo\", \"ya\"]);\nconsole.log(it.next().value); // 'yo'\nconsole.log(it.next().value); // 'ya'\nconsole.log(it.next().done); // true\nInfinite iterator\nfunction idMaker() {\nlet index = 0;\nreturn {\nnext() {\nreturn {\nvalue: index++,\ndone: false,\n};\n},\n};\n}\nconst it = idMaker();\nconsole.log(it.next().value); // 0\nconsole.log(it.next().value); // 1\nconsole.log(it.next().value); // 2\n// \u2026\nDefining an iterable with a generator\nfunction* makeGenerator(array) {\nlet nextIndex = 0;\nwhile (nextIndex < array.length) {\nyield array[nextIndex++];\n}\n}\nconst gen = makeGenerator([\"yo\", \"ya\"]);\nconsole.log(gen.next().value); // 'yo'\nconsole.log(gen.next().value); // 'ya'\nconsole.log(gen.next().done); // true\nfunction* idMaker() {\nlet index = 0;\nwhile (true) {\nyield index++;\n}\n}\nconst it = idMaker();\nconsole.log(it.next().value); // 0\nconsole.log(it.next().value); // 1\nconsole.log(it.next().value); // 2\n// \u2026\nDefining an iterable with a class\nState encapsulation can be done with private fields as well.\nclass SimpleClass {\n#data;\nconstructor(data) {\nthis.#data = data;\n}\n[Symbol.iterator]() {\n// Use a new index for each iterator. This makes multiple\n// iterations over the iterable safe for non-trivial cases,\n// such as use of break or nested looping over the same iterable.\nlet index = 0;\nreturn {\n// Note: using an arrow function allows `this` to point to the\n// one of `[Symbol.iterator]()` instead of `next()`\nnext: () => {\nif (index >= this.#data.length) {\nreturn { done: true };\n}\nreturn { value: this.#data[index++], done: false };\n},\n};\n}\n}\nconst simple = new SimpleClass([1, 2, 3, 4, 5]);\nfor (const val of simple) {\nconsole.log(val); // 1 2 3 4 5\n}\nOverriding built-in iterables\nFor example, a String\nis a built-in iterable object:\nconst someString = \"hi\";\nconsole.log(typeof someString[Symbol.iterator]); // \"function\"\nString\n's default iterator returns the string's code points one by one:\nconst iterator = someString[Symbol.iterator]();\nconsole.log(`${iterator}`); // \"[object String Iterator]\"\nconsole.log(iterator.next()); // { value: \"h\", done: false }\nconsole.log(iterator.next()); // { value: \"i\", done: false }\nconsole.log(iterator.next()); // { value: undefined, done: true }\nYou can redefine the iteration behavior by supplying our own [Symbol.iterator]()\n:\n// need to construct a String object explicitly to avoid auto-boxing\nconst someString = new String(\"hi\");\nsomeString[Symbol.iterator] = function () {\nreturn {\n// this is the iterator object, returning a single element (the string \"bye\")\nnext() {\nreturn this._first\n? { value: \"bye\", done: (this._first = false) }\n: { done: true };\n},\n_first: true,\n};\n};\nNotice how redefining [Symbol.iterator]()\naffects the behavior of built-in constructs that use the iteration protocol:\nconsole.log([...someString]); // [\"bye\"]\nconsole.log(`${someString}`); // \"hi\"\nConcurrent modifications when iterating\nAlmost all iterables have the same underlying semantic: they don't copy the data at the time when iteration starts. Rather, they keep a pointer and move it around. Therefore, if you add, delete, or modify elements in the collection while iterating over the collection, you may inadvertently change whether other unchanged elements in the collection are visited. This is very similar to how iterative array methods work.\nConsider the following case using a URLSearchParams\n:\nconst searchParams = new URLSearchParams(\n\"deleteme1=value1&key2=value2&key3=value3\",\n);\n// Delete unwanted keys\nfor (const [key, value] of searchParams) {\nconsole.log(key);\nif (key.startsWith(\"deleteme\")) {\nsearchParams.delete(key);\n}\n}\n// Output:\n// deleteme1\n// key3\nNote how it never logs key2\n. This is because a URLSearchParams\nis underlyingly a list of key-value pairs. When deleteme1\nis visited and deleted, all other entries are shifted to the left by one, so key2\noccupies the position that deleteme1\nused to be in, and when the pointer moves to the next key, it lands on key3\n.\nCertain iterable implementations avoid this problem by setting \"tombstone\" values to avoid shifting the remaining values. Consider the similar code using a Map\n:\nconst myMap = new Map([\n[\"deleteme1\", \"value1\"],\n[\"key2\", \"value2\"],\n[\"key3\", \"value3\"],\n]);\nfor (const [key, value] of myMap) {\nconsole.log(key);\nif (key.startsWith(\"deleteme\")) {\nmyMap.delete(key);\n}\n}\n// Output:\n// deleteme1\n// key2\n// key3\nNote how it logs all keys. This is because Map\ndoesn't shift the remaining keys when one is deleted. If you want to implement something similar, here's how it may look:\nconst tombstone = Symbol(\"tombstone\");\nclass MyIterable {\n#data;\nconstructor(data) {\nthis.#data = data;\n}\ndelete(deletedKey) {\nfor (let i = 0; i < this.#data.length; i++) {\nif (this.#data[i][0] === deletedKey) {\nthis.#data[i] = tombstone;\nreturn true;\n}\n}\nreturn false;\n}\n*[Symbol.iterator]() {\nfor (const data of this.#data) {\nif (data !== tombstone) {\nyield data;\n}\n}\n}\n}\nconst myIterable = new MyIterable([\n[\"deleteme1\", \"value1\"],\n[\"key2\", \"value2\"],\n[\"key3\", \"value3\"],\n]);\nfor (const [key, value] of myIterable) {\nconsole.log(key);\nif (key.startsWith(\"deleteme\")) {\nmyIterable.delete(key);\n}\n}\nWarning: Concurrent modifications, in general, are very bug-prone and confusing. Unless you know precisely how the iterable is implemented, it's best to avoid modifying the collection while iterating over it.\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-iteration |", "code_snippets": ["// Satisfies both the Iterator Protocol and Iterable\nconst myIterator = {\n next() {\n // \u2026\n },\n [Symbol.iterator]() {\n return this;\n },\n};\n", "const generatorObject = (function* () {\n yield 1;\n yield 2;\n yield 3;\n})();\n\nconsole.log(typeof generatorObject.next);\n// \"function\" \u2014 it has a next method (which returns the right result), so it's an iterator\n\nconsole.log(typeof generatorObject[Symbol.iterator]);\n// \"function\" \u2014 it has a [Symbol.iterator] method (which returns the right iterator), so it's an iterable\n\nconsole.log(generatorObject[Symbol.iterator]() === generatorObject);\n// true \u2014 its [Symbol.iterator] method returns itself (an iterator), so it's an iterable iterator\n", "const myObj = {};\n\nnew WeakSet(\n (function* () {\n yield {};\n yield myObj;\n yield {};\n })(),\n).has(myObj); // true\n", "for (const value of [\"a\", \"b\", \"c\"]) {\n console.log(value);\n}\n// \"a\"\n// \"b\"\n// \"c\"\n\nconsole.log([...\"abc\"]); // [\"a\", \"b\", \"c\"]\n\nfunction* gen() {\n yield* [\"a\", \"b\", \"c\"];\n}\n\nconsole.log(gen().next()); // { value: \"a\", done: false }\n\n[a, b, c] = new Set([\"a\", \"b\", \"c\"]);\nconsole.log(a); // \"a\"\n", "const obj = {\n [Symbol.iterator]() {\n let i = 0;\n return {\n next() {\n i++;\n console.log(\"Returning\", i);\n if (i === 3) return { done: true, value: i };\n return { done: false, value: i };\n },\n return() {\n console.log(\"Closing\");\n return { done: true };\n },\n };\n },\n};\n\nconst [a] = obj;\n// Returning 1\n// Closing\n\nconst [b, c, d] = obj;\n// Returning 1\n// Returning 2\n// Returning 3\n// Already reached the end (the last call returned `done: true`),\n// so `return` is not called\nconsole.log([b, c, d]); // [1, 2, undefined]; the value associated with `done: true` is not reachable\n\nfor (const b of obj) {\n break;\n}\n// Returning 1\n// Closing\n", "const nonWellFormedIterable = { [Symbol.iterator]: 1 };\n[...nonWellFormedIterable]; // TypeError: nonWellFormedIterable is not iterable\nnonWellFormedIterable[Symbol.iterator] = () => 1;\n[...nonWellFormedIterable]; // TypeError: [Symbol.iterator]() returned a non-object value\nnonWellFormedIterable[Symbol.iterator] = () => ({});\n[...nonWellFormedIterable]; // TypeError: nonWellFormedIterable[Symbol.iterator]().next is not a function\n", "try {\n for (const value of iterable) {\n // \u2026\n }\n} catch (e) {\n // Handle the error\n}\n", "function* gen() {\n try {\n yield doSomething();\n yield doSomethingElse();\n } finally {\n cleanup();\n }\n}\n", "const myIterable = {\n *[Symbol.iterator]() {\n yield 1;\n yield 2;\n yield 3;\n },\n};\n\nconsole.log([...myIterable]); // [1, 2, 3]\n", "function makeIterator(array) {\n let nextIndex = 0;\n return {\n next() {\n return nextIndex < array.length\n ? {\n value: array[nextIndex++],\n done: false,\n }\n : {\n done: true,\n };\n },\n };\n}\n\nconst it = makeIterator([\"yo\", \"ya\"]);\n\nconsole.log(it.next().value); // 'yo'\nconsole.log(it.next().value); // 'ya'\nconsole.log(it.next().done); // true\n", "function idMaker() {\n let index = 0;\n return {\n next() {\n return {\n value: index++,\n done: false,\n };\n },\n };\n}\n\nconst it = idMaker();\n\nconsole.log(it.next().value); // 0\nconsole.log(it.next().value); // 1\nconsole.log(it.next().value); // 2\n// \u2026\n", "function* makeGenerator(array) {\n let nextIndex = 0;\n while (nextIndex < array.length) {\n yield array[nextIndex++];\n }\n}\n\nconst gen = makeGenerator([\"yo\", \"ya\"]);\n\nconsole.log(gen.next().value); // 'yo'\nconsole.log(gen.next().value); // 'ya'\nconsole.log(gen.next().done); // true\n\nfunction* idMaker() {\n let index = 0;\n while (true) {\n yield index++;\n }\n}\n\nconst it = idMaker();\n\nconsole.log(it.next().value); // 0\nconsole.log(it.next().value); // 1\nconsole.log(it.next().value); // 2\n// \u2026\n", "class SimpleClass {\n #data;\n\n constructor(data) {\n this.#data = data;\n }\n\n [Symbol.iterator]() {\n // Use a new index for each iterator. This makes multiple\n // iterations over the iterable safe for non-trivial cases,\n // such as use of break or nested looping over the same iterable.\n let index = 0;\n\n return {\n // Note: using an arrow function allows `this` to point to the\n // one of `[Symbol.iterator]()` instead of `next()`\n next: () => {\n if (index >= this.#data.length) {\n return { done: true };\n }\n return { value: this.#data[index++], done: false };\n },\n };\n }\n}\n\nconst simple = new SimpleClass([1, 2, 3, 4, 5]);\n\nfor (const val of simple) {\n console.log(val); // 1 2 3 4 5\n}\n", "const someString = \"hi\";\nconsole.log(typeof someString[Symbol.iterator]); // \"function\"\n", "const iterator = someString[Symbol.iterator]();\nconsole.log(`${iterator}`); // \"[object String Iterator]\"\n\nconsole.log(iterator.next()); // { value: \"h\", done: false }\nconsole.log(iterator.next()); // { value: \"i\", done: false }\nconsole.log(iterator.next()); // { value: undefined, done: true }\n", "// need to construct a String object explicitly to avoid auto-boxing\nconst someString = new String(\"hi\");\n\nsomeString[Symbol.iterator] = function () {\n return {\n // this is the iterator object, returning a single element (the string \"bye\")\n next() {\n return this._first\n ? { value: \"bye\", done: (this._first = false) }\n : { done: true };\n },\n _first: true,\n };\n};\n", "console.log([...someString]); // [\"bye\"]\nconsole.log(`${someString}`); // \"hi\"\n", "const searchParams = new URLSearchParams(\n \"deleteme1=value1&key2=value2&key3=value3\",\n);\n\n// Delete unwanted keys\nfor (const [key, value] of searchParams) {\n console.log(key);\n if (key.startsWith(\"deleteme\")) {\n searchParams.delete(key);\n }\n}\n\n// Output:\n// deleteme1\n// key3\n", "const myMap = new Map([\n [\"deleteme1\", \"value1\"],\n [\"key2\", \"value2\"],\n [\"key3\", \"value3\"],\n]);\n\nfor (const [key, value] of myMap) {\n console.log(key);\n if (key.startsWith(\"deleteme\")) {\n myMap.delete(key);\n }\n}\n\n// Output:\n// deleteme1\n// key2\n// key3\n", "const tombstone = Symbol(\"tombstone\");\n\nclass MyIterable {\n #data;\n constructor(data) {\n this.#data = data;\n }\n delete(deletedKey) {\n for (let i = 0; i < this.#data.length; i++) {\n if (this.#data[i][0] === deletedKey) {\n this.#data[i] = tombstone;\n return true;\n }\n }\n return false;\n }\n *[Symbol.iterator]() {\n for (const data of this.#data) {\n if (data !== tombstone) {\n yield data;\n }\n }\n }\n}\n\nconst myIterable = new MyIterable([\n [\"deleteme1\", \"value1\"],\n [\"key2\", \"value2\"],\n [\"key3\", \"value3\"],\n]);\nfor (const [key, value] of myIterable) {\n console.log(key);\n if (key.startsWith(\"deleteme\")) {\n myIterable.delete(key);\n }\n}\n"], "language": "JavaScript", "source": "mdn", "token_count": 7539} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Duration/milliseconds", "title": "Temporal.Duration.prototype.milliseconds", "content": "Temporal.Duration.prototype.milliseconds\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe milliseconds\naccessor property of Temporal.Duration\ninstances returns an integer representing the number of milliseconds in the duration.\nUnless the duration is balanced, you cannot assume the range of this value, but you can know its sign by checking the duration's sign\nproperty. If it is balanced to a unit above milliseconds, the milliseconds\nabsolute value will be between 0 and 999, inclusive.\nThe set accessor of milliseconds\nis undefined\n. You cannot change this property directly. Use the with()\nmethod to create a new Temporal.Duration\nobject with the desired new value.\nExamples\nUsing milliseconds\njs\nconst d1 = Temporal.Duration.from({ seconds: 1, milliseconds: 500 });\nconst d2 = Temporal.Duration.from({ seconds: -1, milliseconds: -500 });\nconst d3 = Temporal.Duration.from({ seconds: 1 });\nconst d4 = Temporal.Duration.from({ milliseconds: 1000 });\nconsole.log(d1.milliseconds); // 500\nconsole.log(d2.milliseconds); // -500\nconsole.log(d3.milliseconds); // 0\nconsole.log(d4.milliseconds); // 1000\n// Balance d4\nconst d4Balanced = d4.round({ largestUnit: \"seconds\" });\nconsole.log(d4Balanced.milliseconds); // 0\nconsole.log(d4Balanced.seconds); // 1\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-get-temporal.duration.prototype.milliseconds |\nBrowser compatibility\nSee also\nTemporal.Duration\nTemporal.Duration.prototype.years\nTemporal.Duration.prototype.months\nTemporal.Duration.prototype.weeks\nTemporal.Duration.prototype.days\nTemporal.Duration.prototype.hours\nTemporal.Duration.prototype.minutes\nTemporal.Duration.prototype.seconds\nTemporal.Duration.prototype.microseconds\nTemporal.Duration.prototype.nanoseconds", "code_snippets": ["const d1 = Temporal.Duration.from({ seconds: 1, milliseconds: 500 });\nconst d2 = Temporal.Duration.from({ seconds: -1, milliseconds: -500 });\nconst d3 = Temporal.Duration.from({ seconds: 1 });\nconst d4 = Temporal.Duration.from({ milliseconds: 1000 });\n\nconsole.log(d1.milliseconds); // 500\nconsole.log(d2.milliseconds); // -500\nconsole.log(d3.milliseconds); // 0\nconsole.log(d4.milliseconds); // 1000\n\n// Balance d4\nconst d4Balanced = d4.round({ largestUnit: \"seconds\" });\nconsole.log(d4Balanced.milliseconds); // 0\nconsole.log(d4Balanced.seconds); // 1\n"], "language": "JavaScript", "source": "mdn", "token_count": 588} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf", "title": "Date.prototype.valueOf()", "content": "Date.prototype.valueOf()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe valueOf()\nmethod of Date\ninstances returns the number of milliseconds for this date since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.\nTry it\nconst date1 = new Date(Date.UTC(96, 1, 2, 3, 4, 5));\nconsole.log(date1.valueOf());\n// Expected output: 823230245000\nconst date2 = new Date(\"02 Feb 1996 03:04:05 GMT\");\nconsole.log(date2.valueOf());\n// Expected output: 823230245000\nSyntax\nvalueOf()\nParameters\nNone.\nReturn value\nA number representing the timestamp, in milliseconds, of this date. Returns NaN\nif the date is invalid.\nDescription\nThe valueOf()\nmethod is part of the type coercion protocol. Because Date\nhas a [Symbol.toPrimitive]()\nmethod, that method always takes priority over valueOf()\nwhen a Date\nobject is implicitly coerced to a number. However, Date.prototype[Symbol.toPrimitive]()\nstill calls this.valueOf()\ninternally.\nThe Date\nobject overrides the valueOf()\nmethod of Object\n. Date.prototype.valueOf()\nreturns the timestamp of the date, which is functionally equivalent to the Date.prototype.getTime()\nmethod.\nExamples\nUsing valueOf()\nconst d = new Date(0); // 1970-01-01T00:00:00.000Z\nconsole.log(d.valueOf()); // 0\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-date.prototype.valueof |", "code_snippets": ["const date1 = new Date(Date.UTC(96, 1, 2, 3, 4, 5));\n\nconsole.log(date1.valueOf());\n// Expected output: 823230245000\n\nconst date2 = new Date(\"02 Feb 1996 03:04:05 GMT\");\n\nconsole.log(date2.valueOf());\n// Expected output: 823230245000\n", "valueOf()\n", "const d = new Date(0); // 1970-01-01T00:00:00.000Z\nconsole.log(d.valueOf()); // 0\n"], "language": "JavaScript", "source": "mdn", "token_count": 451} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTemporalInstant/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/date/totemporalinstant/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 40} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare", "title": "Intl.Collator.prototype.compare()", "content": "Intl.Collator.prototype.compare()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since September 2017.\nThe compare()\nmethod of Intl.Collator\ninstances compares two\nstrings according to the sort order of this collator object.\nTry it\nconst enCollator = new Intl.Collator(\"en\");\nconst deCollator = new Intl.Collator(\"de\");\nconst svCollator = new Intl.Collator(\"sv\");\nconsole.log(enCollator.compare(\"z\", \"a\") > 0);\n// Expected output: true\nconsole.log(deCollator.compare(\"z\", \"\u00e4\") > 0);\n// Expected output: true\nconsole.log(svCollator.compare(\"z\", \"\u00e4\") > 0);\n// Expected output: false\nSyntax\njs\ncompare(string1, string2)\nParameters\nstring1\n,string2\n-\nThe strings to compare against each other.\nReturn value\nA number indicating how string1\nand string2\ncompare to each other according to the sort order of this Intl.Collator\nobject:\n- A negative value if\nstring1\ncomes beforestring2\n; - A positive value if\nstring1\ncomes afterstring2\n; - 0 if they are considered equal.\nExamples\nUsing compare for array sort\nUse the compare\nfunction for sorting arrays. Note that the function\nis bound to the collator from which it was obtained, so it can be passed directly to\nArray.prototype.sort()\n.\njs\nconst a = [\"Offenbach\", \"\u00d6sterreich\", \"Odenwald\"];\nconst collator = new Intl.Collator(\"de-u-co-phonebk\");\na.sort(collator.compare);\nconsole.log(a.join(\", \")); // \"Odenwald, \u00d6sterreich, Offenbach\"\nUsing compare for array search\nUse the compare\nfunction for finding matching strings in arrays:\njs\nconst a = [\"Congr\u00e8s\", \"congres\", \"Assembl\u00e9e\", \"poisson\"];\nconst collator = new Intl.Collator(\"fr\", {\nusage: \"search\",\nsensitivity: \"base\",\n});\nconst s = \"congres\";\nconst matches = a.filter((v) => collator.compare(v, s) === 0);\nconsole.log(matches.join(\", \")); // \"Congr\u00e8s, congres\"\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # sec-intl.collator.prototype.compare |", "code_snippets": ["const enCollator = new Intl.Collator(\"en\");\nconst deCollator = new Intl.Collator(\"de\");\nconst svCollator = new Intl.Collator(\"sv\");\n\nconsole.log(enCollator.compare(\"z\", \"a\") > 0);\n// Expected output: true\n\nconsole.log(deCollator.compare(\"z\", \"\u00e4\") > 0);\n// Expected output: true\n\nconsole.log(svCollator.compare(\"z\", \"\u00e4\") > 0);\n// Expected output: false\n", "compare(string1, string2)\n", "const a = [\"Offenbach\", \"\u00d6sterreich\", \"Odenwald\"];\nconst collator = new Intl.Collator(\"de-u-co-phonebk\");\na.sort(collator.compare);\nconsole.log(a.join(\", \")); // \"Odenwald, \u00d6sterreich, Offenbach\"\n", "const a = [\"Congr\u00e8s\", \"congres\", \"Assembl\u00e9e\", \"poisson\"];\nconst collator = new Intl.Collator(\"fr\", {\n usage: \"search\",\n sensitivity: \"base\",\n});\nconst s = \"congres\";\nconst matches = a.filter((v) => collator.compare(v, s) === 0);\nconsole.log(matches.join(\", \")); // \"Congr\u00e8s, congres\"\n"], "language": "JavaScript", "source": "mdn", "token_count": 714} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/More_arguments_needed/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/errors/more_arguments_needed/index.md\n\n# Original Wiki contributors\nfscholz\nBzbarsky\nPatrickKettner\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 53} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super", "title": "super", "content": "super\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since March 2016.\nThe super\nkeyword is used to access properties on an object literal or class's [[Prototype]], or invoke a superclass's constructor.\nThe super.prop\nand super[expr]\nexpressions are valid in any method definition in both classes and object literals. The super(...args)\nexpression is valid in class constructors.\nTry it\nclass Foo {\nconstructor(name) {\nthis.name = name;\n}\ngetNameSeparator() {\nreturn \"-\";\n}\n}\nclass FooBar extends Foo {\nconstructor(name, index) {\nsuper(name);\nthis.index = index;\n}\n// Does not get called\ngetNameSeparator() {\nreturn \"/\";\n}\ngetFullName() {\nreturn this.name + super.getNameSeparator() + this.index;\n}\n}\nconst firstFooBar = new FooBar(\"foo\", 1);\nconsole.log(firstFooBar.name);\n// Expected output: \"foo\"\nconsole.log(firstFooBar.getFullName());\n// Expected output: \"foo-1\"\nSyntax\nsuper()\nsuper(arg1)\nsuper(arg1, arg2)\nsuper(arg1, arg2, /* \u2026, */ argN)\nsuper.propertyOnParent\nsuper[expression]\nDescription\nThe super\nkeyword can be used in two ways: as a \"function call\" (super(...args)\n), or as a \"property lookup\" (super.prop\nand super[expr]\n).\nNote:\nsuper\nis a keyword and these are special syntactic constructs. super\nis not a variable that points to the prototype object. Attempting to read super\nitself is a SyntaxError\n.\nconst child = {\nmyParent() {\nconsole.log(super); // SyntaxError: 'super' keyword unexpected here\n},\n};\nIn the constructor body of a derived class (with extends\n), the super\nkeyword may appear as a \"function call\" (super(...args)\n), which must be called before the this\nkeyword is used, and before the constructor returns. It calls the parent class's constructor and binds the parent class's public fields, after which the derived class's constructor can further access and modify this\n.\nThe \"property lookup\" form can be used to access methods and properties of an object literal's or class's [[Prototype]]. Within a class's body, the reference of super\ncan be either the superclass's constructor itself, or the constructor's prototype\n, depending on whether the execution context is instance creation or class initialization. See the Examples section for more details.\nNote that the reference of super\nis determined by the class or object literal super\nwas declared in, not the object the method is called on. Therefore, unbinding or re-binding a method doesn't change the reference of super\nin it (although they do change the reference of this\n). You can see super\nas a variable in the class or object literal scope, which the methods create a closure over. (But also beware that it's not actually a variable, as explained above.)\nWhen setting properties through super\n, the property is set on this\ninstead.\nExamples\nUsing super in classes\nThis code snippet is taken from the classes sample (live demo). Here super()\nis called to avoid duplicating the constructor parts' that are common between Rectangle\nand Square\n.\nclass Rectangle {\nconstructor(height, width) {\nthis.name = \"Rectangle\";\nthis.height = height;\nthis.width = width;\n}\nsayName() {\nconsole.log(`Hi, I am a ${this.name}.`);\n}\nget area() {\nreturn this.height * this.width;\n}\nset area(value) {\nthis._area = value;\n}\n}\nclass Square extends Rectangle {\nconstructor(length) {\n// Here, it calls the parent class's constructor with lengths\n// provided for the Rectangle's width and height\nsuper(length, length);\n// Note: In derived classes, super() must be called before you\n// can use 'this'. Moving this to the top causes a ReferenceError.\nthis.name = \"Square\";\n}\n}\nSuper-calling static methods\nYou are also able to call super on static methods.\nclass Rectangle {\nstatic logNbSides() {\nreturn \"I have 4 sides\";\n}\n}\nclass Square extends Rectangle {\nstatic logDescription() {\nreturn `${super.logNbSides()} which are all equal`;\n}\n}\nSquare.logDescription(); // 'I have 4 sides which are all equal'\nAccessing super in class field declaration\nsuper\ncan also be accessed during class field initialization. The reference of super\ndepends on whether the current field is an instance field or a static field.\nclass Base {\nstatic baseStaticField = 90;\nbaseMethod() {\nreturn 10;\n}\n}\nclass Extended extends Base {\nextendedField = super.baseMethod(); // 10\nstatic extendedStaticField = super.baseStaticField; // 90\n}\nNote that instance fields are set on the instance instead of the constructor's prototype\n, so you can't use super\nto access the instance field of a superclass.\nclass Base {\nbaseField = 10;\n}\nclass Extended extends Base {\nextendedField = super.baseField; // undefined\n}\nHere, extendedField\nis undefined\ninstead of 10, because baseField\nis defined as an own property of the Base\ninstance, instead of Base.prototype\n. super\n, in this context, only looks up properties on Base.prototype\n, because that's the [[Prototype]] of Extended.prototype\n.\nDeleting super properties will throw an error\nYou cannot use the delete\noperator and super.prop\nor super[expr]\nto delete a parent class' property \u2014 it will throw a ReferenceError\n.\nclass Base {\nfoo() {}\n}\nclass Derived extends Base {\ndelete() {\ndelete super.foo; // this is bad\n}\n}\nnew Derived().delete(); // ReferenceError: invalid delete involving 'super'.\nUsing super.prop in object literals\nSuper can also be used in the object initializer notation. In this example, two objects define a method. In the second object, super\ncalls the first object's method. This works with the help of Object.setPrototypeOf()\nwith which we are able to set the prototype of obj2\nto obj1\n, so that super\nis able to find method1\non obj1\n.\nconst obj1 = {\nmethod1() {\nconsole.log(\"method 1\");\n},\n};\nconst obj2 = {\nmethod2() {\nsuper.method1();\n},\n};\nObject.setPrototypeOf(obj2, obj1);\nobj2.method2(); // Logs \"method 1\"\nMethods that read super.prop do not behave differently when bound to other objects\nAccessing super.x\nbehaves like Reflect.get(Object.getPrototypeOf(objectLiteral), \"x\", this)\n, which means the property is always sought on the object literal/class declaration's prototype, and unbinding and re-binding a method won't change the reference of super\n.\nclass Base {\nbaseGetX() {\nreturn 1;\n}\n}\nclass Extended extends Base {\ngetX() {\nreturn super.baseGetX();\n}\n}\nconst e = new Extended();\nconsole.log(e.getX()); // 1\nconst { getX } = e;\nconsole.log(getX()); // 1\nThe same happens in object literals.\nconst parent1 = { prop: 1 };\nconst parent2 = { prop: 2 };\nconst child = {\nmyParent() {\nconsole.log(super.prop);\n},\n};\nObject.setPrototypeOf(child, parent1);\nchild.myParent(); // Logs \"1\"\nconst myParent = child.myParent;\nmyParent(); // Still logs \"1\"\nconst anotherChild = { __proto__: parent2, myParent };\nanotherChild.myParent(); // Still logs \"1\"\nOnly resetting the entire inheritance chain will change the reference of super\n.\nclass Base {\nbaseGetX() {\nreturn 1;\n}\nstatic staticBaseGetX() {\nreturn 3;\n}\n}\nclass AnotherBase {\nbaseGetX() {\nreturn 2;\n}\nstatic staticBaseGetX() {\nreturn 4;\n}\n}\nclass Extended extends Base {\ngetX() {\nreturn super.baseGetX();\n}\nstatic staticGetX() {\nreturn super.staticBaseGetX();\n}\n}\nconst e = new Extended();\n// Reset instance inheritance\nObject.setPrototypeOf(Extended.prototype, AnotherBase.prototype);\nconsole.log(e.getX()); // Logs \"2\" instead of \"1\", because the prototype chain has changed\nconsole.log(Extended.staticGetX()); // Still logs \"3\", because we haven't modified the static part yet\n// Reset static inheritance\nObject.setPrototypeOf(Extended, AnotherBase);\nconsole.log(Extended.staticGetX()); // Now logs \"4\"\nCalling methods from super\nWhen calling super.prop\nas a function, the this\nvalue inside the prop\nfunction is the current this\n, not the object that super\npoints to. For example, the super.getName()\ncall logs \"Extended\"\n, despite the code looking like it's equivalent to Base.getName()\n.\nclass Base {\nstatic getName() {\nconsole.log(this.name);\n}\n}\nclass Extended extends Base {\nstatic getName() {\nsuper.getName();\n}\n}\nExtended.getName(); // Logs \"Extended\"\nThis is especially important when interacting with static private elements.\nSetting super.prop sets the property on this instead\nSetting properties of super\n, such as super.x = 1\n, behaves like Reflect.set(Object.getPrototypeOf(objectLiteral), \"x\", 1, this)\n. This is one of the cases where understanding super\nas simply \"reference of the prototype object\" falls short, because it actually sets the property on this\ninstead.\nclass A {}\nclass B extends A {\nsetX() {\nsuper.x = 1;\n}\n}\nconst b = new B();\nb.setX();\nconsole.log(b); // B { x: 1 }\nconsole.log(Object.hasOwn(b, \"x\")); // true\nsuper.x = 1\nwill look for the property descriptor of x\non A.prototype\n(and invoke the setters defined there), but the this\nvalue will be set to this\n, which is b\nin this context. You can read Reflect.set\nfor more details on the case when target\nand receiver\ndiffer.\nThis means that while methods that get super.prop\nare usually not susceptible to changes in the this\ncontext, those that set super.prop\nare.\n/* Reusing same declarations as above */\nconst b2 = new B();\nb2.setX.call(null); // TypeError: Cannot assign to read only property 'x' of object 'null'\nHowever, super.x = 1\nstill consults the property descriptor of the prototype object, which means you cannot rewrite non-writable properties, and setters will be invoked.\nclass X {\nconstructor() {\n// Create a non-writable property\nObject.defineProperty(this, \"prop\", {\nconfigurable: true,\nwritable: false,\nvalue: 1,\n});\n}\n}\nclass Y extends X {\nconstructor() {\nsuper();\n}\nfoo() {\nsuper.prop = 2; // Cannot overwrite the value.\n}\n}\nconst y = new Y();\ny.foo(); // TypeError: \"prop\" is read-only\nconsole.log(y.prop); // 1\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-super-keyword |", "code_snippets": ["class Foo {\n constructor(name) {\n this.name = name;\n }\n\n getNameSeparator() {\n return \"-\";\n }\n}\n\nclass FooBar extends Foo {\n constructor(name, index) {\n super(name);\n this.index = index;\n }\n\n // Does not get called\n getNameSeparator() {\n return \"/\";\n }\n\n getFullName() {\n return this.name + super.getNameSeparator() + this.index;\n }\n}\n\nconst firstFooBar = new FooBar(\"foo\", 1);\n\nconsole.log(firstFooBar.name);\n// Expected output: \"foo\"\n\nconsole.log(firstFooBar.getFullName());\n// Expected output: \"foo-1\"\n", "super()\nsuper(arg1)\nsuper(arg1, arg2)\nsuper(arg1, arg2, /* \u2026, */ argN)\n\nsuper.propertyOnParent\nsuper[expression]\n", "const child = {\n myParent() {\n console.log(super); // SyntaxError: 'super' keyword unexpected here\n },\n};\n", "class Rectangle {\n constructor(height, width) {\n this.name = \"Rectangle\";\n this.height = height;\n this.width = width;\n }\n sayName() {\n console.log(`Hi, I am a ${this.name}.`);\n }\n get area() {\n return this.height * this.width;\n }\n set area(value) {\n this._area = value;\n }\n}\n\nclass Square extends Rectangle {\n constructor(length) {\n // Here, it calls the parent class's constructor with lengths\n // provided for the Rectangle's width and height\n super(length, length);\n\n // Note: In derived classes, super() must be called before you\n // can use 'this'. Moving this to the top causes a ReferenceError.\n this.name = \"Square\";\n }\n}\n", "class Rectangle {\n static logNbSides() {\n return \"I have 4 sides\";\n }\n}\n\nclass Square extends Rectangle {\n static logDescription() {\n return `${super.logNbSides()} which are all equal`;\n }\n}\nSquare.logDescription(); // 'I have 4 sides which are all equal'\n", "class Base {\n static baseStaticField = 90;\n baseMethod() {\n return 10;\n }\n}\n\nclass Extended extends Base {\n extendedField = super.baseMethod(); // 10\n static extendedStaticField = super.baseStaticField; // 90\n}\n", "class Base {\n baseField = 10;\n}\n\nclass Extended extends Base {\n extendedField = super.baseField; // undefined\n}\n", "class Base {\n foo() {}\n}\nclass Derived extends Base {\n delete() {\n delete super.foo; // this is bad\n }\n}\n\nnew Derived().delete(); // ReferenceError: invalid delete involving 'super'.\n", "const obj1 = {\n method1() {\n console.log(\"method 1\");\n },\n};\n\nconst obj2 = {\n method2() {\n super.method1();\n },\n};\n\nObject.setPrototypeOf(obj2, obj1);\nobj2.method2(); // Logs \"method 1\"\n", "class Base {\n baseGetX() {\n return 1;\n }\n}\nclass Extended extends Base {\n getX() {\n return super.baseGetX();\n }\n}\n\nconst e = new Extended();\nconsole.log(e.getX()); // 1\nconst { getX } = e;\nconsole.log(getX()); // 1\n", "const parent1 = { prop: 1 };\nconst parent2 = { prop: 2 };\n\nconst child = {\n myParent() {\n console.log(super.prop);\n },\n};\n\nObject.setPrototypeOf(child, parent1);\nchild.myParent(); // Logs \"1\"\n\nconst myParent = child.myParent;\nmyParent(); // Still logs \"1\"\n\nconst anotherChild = { __proto__: parent2, myParent };\nanotherChild.myParent(); // Still logs \"1\"\n", "class Base {\n baseGetX() {\n return 1;\n }\n static staticBaseGetX() {\n return 3;\n }\n}\nclass AnotherBase {\n baseGetX() {\n return 2;\n }\n static staticBaseGetX() {\n return 4;\n }\n}\nclass Extended extends Base {\n getX() {\n return super.baseGetX();\n }\n static staticGetX() {\n return super.staticBaseGetX();\n }\n}\n\nconst e = new Extended();\n// Reset instance inheritance\nObject.setPrototypeOf(Extended.prototype, AnotherBase.prototype);\nconsole.log(e.getX()); // Logs \"2\" instead of \"1\", because the prototype chain has changed\nconsole.log(Extended.staticGetX()); // Still logs \"3\", because we haven't modified the static part yet\n// Reset static inheritance\nObject.setPrototypeOf(Extended, AnotherBase);\nconsole.log(Extended.staticGetX()); // Now logs \"4\"\n", "class Base {\n static getName() {\n console.log(this.name);\n }\n}\n\nclass Extended extends Base {\n static getName() {\n super.getName();\n }\n}\n\nExtended.getName(); // Logs \"Extended\"\n", "class A {}\nclass B extends A {\n setX() {\n super.x = 1;\n }\n}\n\nconst b = new B();\nb.setX();\nconsole.log(b); // B { x: 1 }\nconsole.log(Object.hasOwn(b, \"x\")); // true\n", "/* Reusing same declarations as above */\n\nconst b2 = new B();\nb2.setX.call(null); // TypeError: Cannot assign to read only property 'x' of object 'null'\n", "class X {\n constructor() {\n // Create a non-writable property\n Object.defineProperty(this, \"prop\", {\n configurable: true,\n writable: false,\n value: 1,\n });\n }\n}\n\nclass Y extends X {\n constructor() {\n super();\n }\n foo() {\n super.prop = 2; // Cannot overwrite the value.\n }\n}\n\nconst y = new Y();\ny.foo(); // TypeError: \"prop\" is read-only\nconsole.log(y.prop); // 1\n"], "language": "JavaScript", "source": "mdn", "token_count": 3621} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/number/min_value/index.md\n\n# Original Wiki contributors\nmfuji09\nvelusgautam\nfscholz\nwbamberg\njameshkramer\nMingun\nSheppy\nethertank\nShimShamSam\nevilpie\nSevenspade\nMgjbot\nPtak82\nMaian\nDria\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 78} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/format", "title": "Intl.DurationFormat.prototype.format()", "content": "Intl.DurationFormat.prototype.format()\nBaseline\n2025\nNewly available\nSince March 2025, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.\nThe format()\nmethod of Intl.DurationFormat\ninstances formats a duration according to the locale and formatting options of this Intl.DurationFormat\nobject.\nSyntax\nformat(duration)\nParameters\nduration\n-\nThe duration object to be formatted. It should include some or all of the following properties:\nyears\n,months\n,weeks\n,days\n,hours\n,minutes\n,seconds\n,milliseconds\n,microseconds\n,nanoseconds\n. Each property's value should be an integer, and their signs should be consistent. This can be aTemporal.Duration\nobject; see theTemporal.Duration\ndocumentation for more information about these properties.\nReturn value\nA string representing the given duration\nformatted according to the locale and formatting options of this Intl.DurationFormat\nobject.\nNote:\nMost of the time, the formatting returned by format()\nis consistent. However, the output may vary between implementations, even within the same locale \u2014 output variations are by design and allowed by the specification. It may also not be what you expect. For example, the string may use non-breaking spaces or be surrounded by bidirectional control characters. You should not compare the results of format()\nto hardcoded constants.\nExamples\nUsing format()\nThe following example shows how to create a Duration formatter using the English language.\nconst duration = {\nyears: 1,\nmonths: 2,\nweeks: 3,\ndays: 3,\nhours: 4,\nminutes: 5,\nseconds: 6,\nmilliseconds: 7,\nmicroseconds: 8,\nnanoseconds: 9,\n};\n// Without options, style defaults to \"short\"\nnew Intl.DurationFormat(\"en\").format(duration);\n// \"1 yr, 2 mths, 3 wks, 3 days, 4 hr, 5 min, 6 sec, 7 ms, 8 \u03bcs, 9 ns\"\n// With style set to \"long\"\nnew Intl.DurationFormat(\"en\", { style: \"long\" }).format(duration);\n// \"1 year, 2 months, 3 weeks, 3 days, 4 hours, 5 minutes, 6 seconds, 7 milliseconds, 8 microseconds, 9 nanoseconds\"\n// With style set to \"narrow\"\nnew Intl.DurationFormat(\"en\", { style: \"narrow\" }).format(duration);\n// \"1y 2mo 3w 3d 4h 5m 6s 7ms 8\u03bcs 9ns\"\nUsing format() with different locales and styles\nconst duration = {\nhours: 1,\nminutes: 46,\nseconds: 40,\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// With style set to \"short\" and locale set to \"en\"\nnew Intl.DurationFormat(\"en\", { style: \"short\" }).format(duration);\n// \"1 hr, 46 min and 40 sec\"\n// With style set to \"short\" and locale set to \"pt\"\nnew Intl.DurationFormat(\"pt\", { style: \"narrow\" }).format(duration);\n// \"1 h 46 min 40 s\"\n// With style set to \"digital\" and locale set to \"en\"\nnew Intl.DurationFormat(\"en\", { style: \"digital\" }).format(duration);\n// \"1:46:40\"\n// With style set to \"digital\", locale set to \"en\", and hours set to \"long\"\nnew Intl.DurationFormat(\"en\", { style: \"digital\", hours: \"long\" }).format(\nduration,\n);\n// \"1 hour, 46:40\"\nUsing format() with the fractionalDigits option\nconst duration = {\nhours: 11,\nminutes: 30,\nseconds: 12,\nmilliseconds: 345,\nmicroseconds: 600,\n};\nnew Intl.DurationFormat(\"en\", { style: \"digital\" }).format(duration);\n// \"11:30:12.3456\"\nnew Intl.DurationFormat(\"en\", { style: \"digital\", fractionalDigits: 5 }).format(\nduration,\n);\n// \"11:30:12.34560\"\nnew Intl.DurationFormat(\"en\", { style: \"digital\", fractionalDigits: 3 }).format(\nduration,\n);\n// \"11:30:12.346\"\nSpecifications\n| Specification |\n|---|\n| Intl.DurationFormat # sec-Intl.DurationFormat.prototype.format |", "code_snippets": ["format(duration)\n", "const duration = {\n years: 1,\n months: 2,\n weeks: 3,\n days: 3,\n hours: 4,\n minutes: 5,\n seconds: 6,\n milliseconds: 7,\n microseconds: 8,\n nanoseconds: 9,\n};\n\n// Without options, style defaults to \"short\"\nnew Intl.DurationFormat(\"en\").format(duration);\n// \"1 yr, 2 mths, 3 wks, 3 days, 4 hr, 5 min, 6 sec, 7 ms, 8 \u03bcs, 9 ns\"\n\n// With style set to \"long\"\nnew Intl.DurationFormat(\"en\", { style: \"long\" }).format(duration);\n// \"1 year, 2 months, 3 weeks, 3 days, 4 hours, 5 minutes, 6 seconds, 7 milliseconds, 8 microseconds, 9 nanoseconds\"\n\n// With style set to \"narrow\"\nnew Intl.DurationFormat(\"en\", { style: \"narrow\" }).format(duration);\n// \"1y 2mo 3w 3d 4h 5m 6s 7ms 8\u03bcs 9ns\"\n", "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 set to \"en\"\nnew Intl.DurationFormat(\"en\", { style: \"short\" }).format(duration);\n// \"1 hr, 46 min and 40 sec\"\n\n// With style set to \"short\" and locale set to \"pt\"\nnew Intl.DurationFormat(\"pt\", { style: \"narrow\" }).format(duration);\n// \"1 h 46 min 40 s\"\n\n// With style set to \"digital\" and locale set to \"en\"\nnew Intl.DurationFormat(\"en\", { style: \"digital\" }).format(duration);\n// \"1:46:40\"\n\n// With style set to \"digital\", locale set to \"en\", and hours set to \"long\"\nnew Intl.DurationFormat(\"en\", { style: \"digital\", hours: \"long\" }).format(\n duration,\n);\n// \"1 hour, 46:40\"\n", "const duration = {\n hours: 11,\n minutes: 30,\n seconds: 12,\n milliseconds: 345,\n microseconds: 600,\n};\n\nnew Intl.DurationFormat(\"en\", { style: \"digital\" }).format(duration);\n// \"11:30:12.3456\"\n\nnew Intl.DurationFormat(\"en\", { style: \"digital\", fractionalDigits: 5 }).format(\n duration,\n);\n// \"11:30:12.34560\"\n\nnew Intl.DurationFormat(\"en\", { style: \"digital\", fractionalDigits: 3 }).format(\n duration,\n);\n// \"11:30:12.346\"\n"], "language": "JavaScript", "source": "mdn", "token_count": 1394} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/json/stringify/index.md\n\n# Original Wiki contributors\ngmanpersona\nmfuji09\nkrvajal\nMaximYaskov\nfscholz\nlionel-rowe\ndfmartin\nWind1808\nchrisdavidmills\nArtoria2e5\ndong-jy\nzeta12ti\nWaldo\nExE-Boss\npre1ude\njohnmorseytest007\npepkin88\nross-u\nZearin_Galaurum\nbmarkovic\nSheppy\nBrettz9\npaury\njonasraoni\nSphinxKnight\nshripal7\nKonrud\nwbamberg\nschalkneethling\nJedipedia\nwisgh\nkubijo\nautra\nvandanasamudrala\njacobp100\njameshkramer\nnmve\nwbhob\nmadarche\nmatthung0807\neduardoboucas\nwhinc\ndoomsterinc\nnickleus\nnoscripter\nandfaulkner\nkevinburkeshyp\nkevinburke\nchris.johnson\nMingun\nziyunfei\nmlissner\nmiller.augusto\ngeorgebatalinski\nstevemao\nmiller_augusto\nenaeseth\npaul.irish\nNickolay\nevilpie\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 199} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_delete/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/errors/cant_delete/index.md\n\n# Original Wiki contributors\nfscholz\nPatrickKettner\nnmve\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 50} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/rawJSON/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/json/rawjson/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 37} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/displayName/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/function/displayname/index.md\n\n# Original Wiki contributors\nfscholz\nmfluehr\nminstrel1977\ngeorgeawg\nMingun\ntoothbrush\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 61} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer", "title": "Object initializer", "content": "Object initializer\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nAn object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}\n). Objects can also be initialized using Object.create()\nor by invoking a constructor function with the new\noperator.\nTry it\nconst object1 = { a: \"foo\", b: 42, c: {} };\nconsole.log(object1.a);\n// Expected output: \"foo\"\nconst a = \"foo\";\nconst b = 42;\nconst c = {};\nconst object2 = { a: a, b: b, c: c };\nconsole.log(object2.b);\n// Expected output: 42\nconst object3 = { a, b, c };\nconsole.log(object3.a);\n// Expected output: \"foo\"\nSyntax\no = {\na: \"foo\",\nb: 42,\nc: {},\n1: \"number literal property\",\n\"foo:bar\": \"string literal property\",\nshorthandProperty,\nmethod(parameters) {\n// \u2026\n},\nget property() {},\nset property(value) {},\n[expression]: \"computed property\",\n__proto__: prototype,\n...spreadProperty,\n};\nDescription\nAn object initializer is an expression that describes the initialization of an Object\n. Objects consist of properties, which are used to describe an object. The values of object properties can either contain primitive data types or other objects.\nObject literal syntax vs. JSON\nThe object literal syntax is not the same as the JavaScript Object Notation (JSON). Although they look similar, there are differences between them:\n- JSON only permits property definition using the\n\"property\": value\nsyntax. The property name must be double-quoted, and the definition cannot be a shorthand. Computed property names are not allowed either. - JSON object property values can only be strings, numbers,\ntrue\n,false\n,null\n, arrays, or another JSON object. This means JSON cannot express methods or non-plain objects likeMap\norRegExp\n. - In JSON,\n\"__proto__\"\nis a normal property key. In an object literal, it sets the object's prototype.\nJSON is a strict subset of the object literal syntax, meaning that every valid JSON text can be parsed as an object literal, and would likely not cause syntax errors. The only exception is that the object literal syntax prohibits duplicate __proto__\nkeys, which does not apply to JSON.parse()\n. The latter treats __proto__\nlike a normal property and takes the last occurrence as the property's value. The only time when the object value they represent (a.k.a. their semantic) differ is also when the source contains the __proto__\nkey \u2014 for object literals, it sets the object's prototype; for JSON, it's a normal property.\nconsole.log(JSON.parse('{ \"__proto__\": 0, \"__proto__\": 1 }')); // {__proto__: 1}\nconsole.log({ \"__proto__\": 0, \"__proto__\": 1 }); // SyntaxError: Duplicate __proto__ fields are not allowed in object literals\nconsole.log(JSON.parse('{ \"__proto__\": {} }')); // { __proto__: {} }\nconsole.log({ \"__proto__\": {} }); // {} (with {} as prototype)\nExamples\nCreating objects\nAn empty object with no properties can be created like this:\nconst object = {};\nHowever, the advantage of the literal or initializer notation is, that you are able to quickly create objects with properties inside the curly braces. You notate a list of key: value\npairs delimited by commas.\nThe following code creates an object with three properties and the keys are \"foo\"\n, \"age\"\nand \"baz\"\n. The values of these keys are a string \"bar\"\n, the number 42\n, and another object.\nconst object = {\nfoo: \"bar\",\nage: 42,\nbaz: { myProp: 12 },\n};\nAccessing properties\nOnce you have created an object, you might want to read or change them. Object properties can be accessed by using the dot notation or the bracket notation. (See property accessors for detailed information.)\nobject.foo; // \"bar\"\nobject[\"age\"]; // 42\nobject.baz; // {myProp: 12}\nobject.baz.myProp; // 12\nProperty definitions\nWe have already learned how to notate properties using the initializer syntax. Oftentimes, there are variables in your code that you would like to put into an object. You will see code like this:\nconst a = \"foo\";\nconst b = 42;\nconst c = {};\nconst o = {\na: a,\nb: b,\nc: c,\n};\nThere is a shorter notation available to achieve the same:\nconst a = \"foo\";\nconst b = 42;\nconst c = {};\n// Shorthand property names\nconst o = { a, b, c };\n// In other words,\nconsole.log(o.a === { a }.a); // true\nDuplicate property names\nWhen using the same name for your properties, the second property will overwrite the first.\nconst a = { x: 1, x: 2 };\nconsole.log(a); // {x: 2}\nAfter ES2015, duplicate property names are allowed everywhere, including strict mode. You can also have duplicate property names in classes. The only exception is private elements, which must be unique in the class body.\nMethod definitions\nA property of an object can also refer to a function or a getter or setter method.\nconst o = {\nproperty: function (parameters) {},\nget property() {\nreturn 1;\n},\nset property(value) {},\n};\nA shorthand notation is available, so that the keyword function\nis no longer necessary.\n// Shorthand method names\nconst o = {\nproperty(parameters) {},\n};\nThere is also a way to concisely define generator methods.\nconst o = {\n*generator() {\n// \u2026\n},\n};\nWhich is equivalent to this ES5-like notation (but note that ECMAScript 5 has no generators):\nconst o = {\ngenerator: function* () {\n// \u2026\n},\n};\nFor more information and examples about methods, see method definitions.\nComputed property names\nThe object initializer syntax also supports computed property names. That allows you to put an expression in square brackets []\n, that will be computed and used as the property name. This is reminiscent of the bracket notation of the property accessor syntax, which you may have used to read and set properties already.\nNow you can use a similar syntax in object literals, too:\n// Computed property names\nlet i = 0;\nconst a = {\n[`foo${++i}`]: i,\n[`foo${++i}`]: i,\n[`foo${++i}`]: i,\n};\nconsole.log(a.foo1); // 1\nconsole.log(a.foo2); // 2\nconsole.log(a.foo3); // 3\nconst items = [\"A\", \"B\", \"C\"];\nconst obj = {\n[items]: \"Hello\",\n};\nconsole.log(obj); // A,B,C: \"Hello\"\nconsole.log(obj[\"A,B,C\"]); // \"Hello\"\nconst param = \"size\";\nconst config = {\n[param]: 12,\n[`mobile${param.charAt(0).toUpperCase()}${param.slice(1)}`]: 4,\n};\nconsole.log(config); // {size: 12, mobileSize: 4}\nSpread properties\nObject literals support the spread syntax. It copies own enumerable properties from a provided object onto a new object.\nShallow-cloning (excluding prototype\n) or merging objects is now possible using a shorter syntax than Object.assign()\n.\nconst obj1 = { foo: \"bar\", x: 42 };\nconst obj2 = { foo: \"baz\", y: 13 };\nconst clonedObj = { ...obj1 };\n// { foo: \"bar\", x: 42 }\nconst mergedObj = { ...obj1, ...obj2 };\n// { foo: \"baz\", x: 42, y: 13 }\nWarning:\nNote that Object.assign()\ntriggers setters, whereas the spread syntax doesn't!\nPrototype setter\nA property definition of the form __proto__: value\nor \"__proto__\": value\ndoes not create a property with the name __proto__\n. Instead, if the provided value is an object or null\n, it points the [[Prototype]]\nof the created object to that value. (If the value is not an object or null\n, the object is not changed.)\nNote that the __proto__\nkey is standardized syntax, in contrast to the non-standard and non-performant Object.prototype.__proto__\naccessors. It sets the [[Prototype]]\nduring object creation, similar to Object.create\n\u2014 instead of mutating the prototype chain.\nconst obj1 = {};\nconsole.log(Object.getPrototypeOf(obj1) === Object.prototype); // true\nconst obj2 = { __proto__: null };\nconsole.log(Object.getPrototypeOf(obj2)); // null\nconst protoObj = {};\nconst obj3 = { \"__proto__\": protoObj };\nconsole.log(Object.getPrototypeOf(obj3) === protoObj); // true\nconst obj4 = { __proto__: \"not an object or null\" };\nconsole.log(Object.getPrototypeOf(obj4) === Object.prototype); // true\nconsole.log(Object.hasOwn(obj4, \"__proto__\")); // false\nOnly a single prototype setter is permitted in an object literal. Multiple prototype setters are a syntax error.\nProperty definitions that do not use \"colon\" notation are not prototype setters. They are property definitions that behave identically to similar definitions using any other name.\nconst __proto__ = \"variable\";\nconst obj1 = { __proto__ };\nconsole.log(Object.getPrototypeOf(obj1) === Object.prototype); // true\nconsole.log(Object.hasOwn(obj1, \"__proto__\")); // true\nconsole.log(obj1.__proto__); // \"variable\"\nconst obj2 = { __proto__() { return \"hello\"; } };\nconsole.log(obj2.__proto__()); // \"hello\"\nconst obj3 = { [\"__proto__\"]: 17 };\nconsole.log(obj3.__proto__); // 17\n// Mixing prototype setter with normal own properties with \"__proto__\" key\nconst obj4 = { [\"__proto__\"]: 17, __proto__: {} }; // {__proto__: 17} (with {} as prototype)\nconst obj5 = {\n[\"__proto__\"]: 17,\n__proto__: {},\n__proto__: null, // SyntaxError: Duplicate __proto__ fields are not allowed in object literals\n};\nconst obj6 = {\n[\"__proto__\"]: 17,\n[\"__proto__\"]: \"hello\",\n__proto__: null,\n}; // {__proto__: \"hello\"} (with null as prototype)\nconst obj7 = {\n[\"__proto__\"]: 17,\n__proto__,\n__proto__: null,\n}; // {__proto__: \"variable\"} (with null as prototype)\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-object-initializer |", "code_snippets": ["const object1 = { a: \"foo\", b: 42, c: {} };\n\nconsole.log(object1.a);\n// Expected output: \"foo\"\n\nconst a = \"foo\";\nconst b = 42;\nconst c = {};\nconst object2 = { a: a, b: b, c: c };\n\nconsole.log(object2.b);\n// Expected output: 42\n\nconst object3 = { a, b, c };\n\nconsole.log(object3.a);\n// Expected output: \"foo\"\n", "o = {\n a: \"foo\",\n b: 42,\n c: {},\n 1: \"number literal property\",\n \"foo:bar\": \"string literal property\",\n\n shorthandProperty,\n\n method(parameters) {\n // \u2026\n },\n\n get property() {},\n set property(value) {},\n\n [expression]: \"computed property\",\n\n __proto__: prototype,\n\n ...spreadProperty,\n};\n", "console.log(JSON.parse('{ \"__proto__\": 0, \"__proto__\": 1 }')); // {__proto__: 1}\nconsole.log({ \"__proto__\": 0, \"__proto__\": 1 }); // SyntaxError: Duplicate __proto__ fields are not allowed in object literals\n\nconsole.log(JSON.parse('{ \"__proto__\": {} }')); // { __proto__: {} }\nconsole.log({ \"__proto__\": {} }); // {} (with {} as prototype)\n", "const object = {};\n", "const object = {\n foo: \"bar\",\n age: 42,\n baz: { myProp: 12 },\n};\n", "object.foo; // \"bar\"\nobject[\"age\"]; // 42\nobject.baz; // {myProp: 12}\nobject.baz.myProp; // 12\n", "const a = \"foo\";\nconst b = 42;\nconst c = {};\n\nconst o = {\n a: a,\n b: b,\n c: c,\n};\n", "const a = \"foo\";\nconst b = 42;\nconst c = {};\n\n// Shorthand property names\nconst o = { a, b, c };\n\n// In other words,\nconsole.log(o.a === { a }.a); // true\n", "const a = { x: 1, x: 2 };\nconsole.log(a); // {x: 2}\n", "const o = {\n property: function (parameters) {},\n get property() {\n return 1;\n },\n set property(value) {},\n};\n", "// Shorthand method names\nconst o = {\n property(parameters) {},\n};\n", "const o = {\n *generator() {\n // \u2026\n },\n};\n", "const o = {\n generator: function* () {\n // \u2026\n },\n};\n", "// Computed property names\nlet i = 0;\nconst a = {\n [`foo${++i}`]: i,\n [`foo${++i}`]: i,\n [`foo${++i}`]: i,\n};\n\nconsole.log(a.foo1); // 1\nconsole.log(a.foo2); // 2\nconsole.log(a.foo3); // 3\n\nconst items = [\"A\", \"B\", \"C\"];\nconst obj = {\n [items]: \"Hello\",\n};\nconsole.log(obj); // A,B,C: \"Hello\"\nconsole.log(obj[\"A,B,C\"]); // \"Hello\"\n\nconst param = \"size\";\nconst config = {\n [param]: 12,\n [`mobile${param.charAt(0).toUpperCase()}${param.slice(1)}`]: 4,\n};\n\nconsole.log(config); // {size: 12, mobileSize: 4}\n", "const obj1 = { foo: \"bar\", x: 42 };\nconst obj2 = { foo: \"baz\", y: 13 };\n\nconst clonedObj = { ...obj1 };\n// { foo: \"bar\", x: 42 }\n\nconst mergedObj = { ...obj1, ...obj2 };\n// { foo: \"baz\", x: 42, y: 13 }\n", "const obj1 = {};\nconsole.log(Object.getPrototypeOf(obj1) === Object.prototype); // true\n\nconst obj2 = { __proto__: null };\nconsole.log(Object.getPrototypeOf(obj2)); // null\n\nconst protoObj = {};\nconst obj3 = { \"__proto__\": protoObj };\nconsole.log(Object.getPrototypeOf(obj3) === protoObj); // true\n\nconst obj4 = { __proto__: \"not an object or null\" };\nconsole.log(Object.getPrototypeOf(obj4) === Object.prototype); // true\nconsole.log(Object.hasOwn(obj4, \"__proto__\")); // false\n", "const __proto__ = \"variable\";\n\nconst obj1 = { __proto__ };\nconsole.log(Object.getPrototypeOf(obj1) === Object.prototype); // true\nconsole.log(Object.hasOwn(obj1, \"__proto__\")); // true\nconsole.log(obj1.__proto__); // \"variable\"\n\nconst obj2 = { __proto__() { return \"hello\"; } };\nconsole.log(obj2.__proto__()); // \"hello\"\n\nconst obj3 = { [\"__proto__\"]: 17 };\nconsole.log(obj3.__proto__); // 17\n\n// Mixing prototype setter with normal own properties with \"__proto__\" key\nconst obj4 = { [\"__proto__\"]: 17, __proto__: {} }; // {__proto__: 17} (with {} as prototype)\nconst obj5 = {\n [\"__proto__\"]: 17,\n __proto__: {},\n __proto__: null, // SyntaxError: Duplicate __proto__ fields are not allowed in object literals\n};\nconst obj6 = {\n [\"__proto__\"]: 17,\n [\"__proto__\"]: \"hello\",\n __proto__: null,\n}; // {__proto__: \"hello\"} (with null as prototype)\nconst obj7 = {\n [\"__proto__\"]: 17,\n __proto__,\n __proto__: null,\n}; // {__proto__: \"variable\"} (with null as prototype)\n"], "language": "JavaScript", "source": "mdn", "token_count": 3283} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/valueOf/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/number/valueof/index.md\n\n# Original Wiki contributors\nmfuji09\nfscholz\nZearin_Galaurum\nalattalatta\nwbamberg\njameshkramer\neduardoboucas\nziyunfei\nMingun\nethertank\nSheppy\nevilpie\nWaldo\nPotappo\nMgjbot\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 81} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/More_arguments_needed", "title": "TypeError: More arguments needed", "content": "TypeError: More arguments needed\nThe JavaScript exception \"more arguments needed\" occurs when there is an error with how a function is called. More arguments need to be provided.\nMessage\nTypeError: Object prototype may only be an Object or null: undefined (V8-based) TypeError: Object.create requires at least 1 argument, but only 0 were passed (Firefox) TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 0 were passed (Firefox) TypeError: Object.defineProperties requires at least 1 argument, but only 0 were passed (Firefox) TypeError: Object prototype may only be an Object or null. (Safari)\nError type\nWhat went wrong?\nThere is an error with how a function is called. More arguments need to be provided.\nExamples\nRequired arguments not provided\nThe Object.create()\nmethod requires at least one argument and the\nObject.setPrototypeOf()\nmethod requires at least two arguments:\njs\nconst obj = Object.create();\n// TypeError: Object.create requires at least 1 argument, but only 0 were passed\nconst obj2 = Object.setPrototypeOf({});\n// TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 1 were passed\nYou can fix this by setting null\nas the prototype, for example:\njs\nconst obj = Object.create(null);\nconst obj2 = Object.setPrototypeOf({}, null);\nSee also\n- Functions guide", "code_snippets": ["const obj = Object.create();\n// TypeError: Object.create requires at least 1 argument, but only 0 were passed\n\nconst obj2 = Object.setPrototypeOf({});\n// TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 1 were passed\n", "const obj = Object.create(null);\n\nconst obj2 = Object.setPrototypeOf({}, null);\n"], "language": "JavaScript", "source": "mdn", "token_count": 409} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/operators/nullish_coalescing/index.md\n\n# Original Wiki contributors\nOtterOne\nsideshowbarker\nBlackBindy\nfscholz\nsnek\nDorward\nneverRare\nkoesper\nZearin_Galaurum\nMik13\nwbamberg\nSphinxKnight\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 75} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Instant/fromEpochMilliseconds", "title": "Temporal.Instant.fromEpochMilliseconds()", "content": "Temporal.Instant.fromEpochMilliseconds()\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe Temporal.Instant.fromEpochMilliseconds()\nstatic method creates a new Temporal.Instant\nobject from the number of milliseconds since the Unix epoch (midnight at the beginning of January 1, 1970, UTC).\nTo convert a Date\nobject to a Temporal.Instant\nobject, use Date.prototype.toTemporalInstant()\ninstead.\nSyntax\njs\nTemporal.Instant.fromEpochMilliseconds(epochMilliseconds)\nParameters\nepochMilliseconds\n-\nA number representing the number of milliseconds since the Unix epoch. Internally, it is converted to a BigInt and multiplied by\n1e6\nto get the number of nanoseconds.\nReturn value\nA new Temporal.Instant\nobject representing the instant in time specified by epochMilliseconds\n.\nExceptions\nRangeError\n-\nThrown in one of the following cases:\nepochMilliseconds\ncannot be converted to a BigInt (e.g., not an integer).epochMilliseconds\nis not in the representable range, which is \u00b1108 days, or about \u00b1273,972.6 years, from the Unix epoch.\nExamples\nUsing Temporal.Instant.fromEpochMilliseconds()\njs\nconst instant = Temporal.Instant.fromEpochMilliseconds(0);\nconsole.log(instant.toString()); // 1970-01-01T00:00:00Z\nconst vostok1Liftoff = Temporal.Instant.fromEpochMilliseconds(-275248380000);\nconsole.log(vostok1Liftoff.toString()); // 1961-04-12T06:07:00Z\nconst sts1Liftoff = Temporal.Instant.fromEpochMilliseconds(355924804000);\nconsole.log(sts1Liftoff.toString()); // 1981-04-12T12:00:04Z\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-temporal.instant.fromepochmilliseconds |", "code_snippets": ["Temporal.Instant.fromEpochMilliseconds(epochMilliseconds)\n", "const instant = Temporal.Instant.fromEpochMilliseconds(0);\nconsole.log(instant.toString()); // 1970-01-01T00:00:00Z\nconst vostok1Liftoff = Temporal.Instant.fromEpochMilliseconds(-275248380000);\nconsole.log(vostok1Liftoff.toString()); // 1961-04-12T06:07:00Z\nconst sts1Liftoff = Temporal.Instant.fromEpochMilliseconds(355924804000);\nconsole.log(sts1Liftoff.toString()); // 1981-04-12T12:00:04Z\n"], "language": "JavaScript", "source": "mdn", "token_count": 523} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Now/plainDateTimeISO/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/temporal/now/plaindatetimeiso/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 42} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder", "title": "Remainder (%)", "content": "Remainder (%)\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe remainder (%\n) operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.\nTry it\nconsole.log(13 % 5);\n// Expected output: 3\nconsole.log(-13 % 5);\n// Expected output: -3\nconsole.log(4 % 2);\n// Expected output: 0\nconsole.log(-4 % 2);\n// Expected output: -0\nSyntax\nx % y\nDescription\nThe %\noperator is overloaded for two types of operands: number and BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt remainder if both operands become BigInts; otherwise, it performs number remainder. A TypeError\nis thrown if one operand becomes a BigInt but the other becomes a number.\nFor the operation n % d\n, n\nis called the dividend and d\nis called the divisor. The operation returns NaN\nif one of the operands is NaN\n, n\nis \u00b1Infinity, or if d\nis \u00b10. Otherwise, if d\nis \u00b1Infinity or if n\nis \u00b10, the dividend n\nis returned.\nWhen both operands are non-zero and finite, the remainder r\nis calculated as r := n - d * q\nwhere q\nis the integer such that r\nhas the same sign as the dividend n\nwhile being as close to 0 as possible.\nNote that while in most languages, '%' is a remainder operator, in some (e.g., Python, Perl) it is a modulo operator. Modulo is defined as k := n - d * q\nwhere q\nis the integer such that k\nhas the same sign as the divisor d\nwhile being as close to 0 as possible. For two values of the same sign, the two are equivalent, but when the operands are of different signs, the modulo result always has the same sign as the divisor, while the remainder has the same sign as the dividend, which can make them differ by one unit of d\n. To obtain a modulo in JavaScript, in place of n % d\n, use ((n % d) + d) % d\n. In JavaScript, the modulo operation (which doesn't have a dedicated operator) is used to normalize the second operand of bitwise shift operators (<<\n, >>\n, etc.), making the offset always a positive value.\nFor BigInt division, a RangeError\nis thrown if the divisor y\nis 0n\n. This is because number remainder by zero returns NaN\n, but BigInt has no concept of NaN\n.\nExamples\nRemainder with positive dividend\n13 % 5; // 3\n1 % -2; // 1\n1 % 2; // 1\n2 % 3; // 2\n5.5 % 2; // 1.5\n3n % 2n; // 1n\nRemainder with negative dividend\n-13 % 5; // -3\n-1 % 2; // -1\n-4 % 2; // -0\n-3n % 2n; // -1n\nRemainder with NaN\nNaN % 2; // NaN\nRemainder with Infinity\nInfinity % 2; // NaN\nInfinity % 0; // NaN\nInfinity % Infinity; // NaN\n2 % Infinity; // 2\n0 % Infinity; // 0\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-multiplicative-operators |", "code_snippets": ["console.log(13 % 5);\n// Expected output: 3\n\nconsole.log(-13 % 5);\n// Expected output: -3\n\nconsole.log(4 % 2);\n// Expected output: 0\n\nconsole.log(-4 % 2);\n// Expected output: -0\n", "x % y\n", "13 % 5; // 3\n1 % -2; // 1\n1 % 2; // 1\n2 % 3; // 2\n5.5 % 2; // 1.5\n\n3n % 2n; // 1n\n", "-13 % 5; // -3\n-1 % 2; // -1\n-4 % 2; // -0\n\n-3n % 2n; // -1n\n", "NaN % 2; // NaN\n", "Infinity % 2; // NaN\nInfinity % 0; // NaN\nInfinity % Infinity; // NaN\n2 % Infinity; // 2\n0 % Infinity; // 0\n"], "language": "JavaScript", "source": "mdn", "token_count": 808} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Now/plainTimeISO", "title": "Temporal.Now.plainTimeISO()", "content": "Temporal.Now.plainTimeISO()\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe Temporal.Now.plainTimeISO()\nstatic method returns the current time as a Temporal.PlainTime\nobject, in the specified time zone.\nNote that although the method contains \"ISO\" in its name, Temporal.PlainTime\nobjects do not have associated calendars, as the time format is not calendar-dependent.\nSyntax\nTemporal.Now.plainTimeISO()\nTemporal.Now.plainTimeISO(timeZone)\nParameters\ntimeZone\nOptional-\nEither a string or a\nTemporal.ZonedDateTime\ninstance representing the time zone to interpret the system time in. If aTemporal.ZonedDateTime\ninstance, 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).\nReturn value\nThe current time in the specified time zone, as a Temporal.PlainTime\nobject. Has the same precision as Temporal.Now.instant()\n.\nExceptions\nRangeError\n-\nThrown if the time zone is invalid.\nExamples\nUsing Temporal.Now.plainTimeISO()\n// The current time in the system's time zone\nconst time = Temporal.Now.plainTimeISO();\nconsole.log(time); // e.g.: 06:12:34.567890123\n// The current time in the \"America/New_York\" time zone\nconst timeInNewYork = Temporal.Now.plainTimeISO(\"America/New_York\");\nconsole.log(timeInNewYork); // e.g.: 23:12:34.567890123\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-temporal.now.plaintimeiso |", "code_snippets": ["Temporal.Now.plainTimeISO()\nTemporal.Now.plainTimeISO(timeZone)\n", "// The current time in the system's time zone\nconst time = Temporal.Now.plainTimeISO();\nconsole.log(time); // e.g.: 06:12:34.567890123\n\n// The current time in the \"America/New_York\" time zone\nconst timeInNewYork = Temporal.Now.plainTimeISO(\"America/New_York\");\nconsole.log(timeInNewYork); // e.g.: 23:12:34.567890123\n"], "language": "JavaScript", "source": "mdn", "token_count": 486} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction", "title": "Subtraction (-)", "content": "Subtraction (-)\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe subtraction (-\n) operator subtracts the two operands, producing their difference.\nTry it\nconsole.log(5 - 3);\n// Expected output: 2\nconsole.log(3.5 - 5);\n// Expected output: -1.5\nconsole.log(5 - \"hello\");\n// Expected output: NaN\nconsole.log(5 - true);\n// Expected output: 4\nSyntax\nx - y\nDescription\nThe -\noperator is overloaded for two types of operands: number and BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt subtraction if both operands become BigInts; otherwise, it performs number subtraction. A TypeError\nis thrown if one operand becomes a BigInt but the other becomes a number.\nExamples\nSubtraction using numbers\n5 - 3; // 2\n3 - 5; // -2\nOther non-BigInt values are coerced to numbers:\n\"foo\" - 3; // NaN; \"foo\" is converted to the number NaN\n5 - \"3\"; // 2; \"3\" is converted to the number 3\nSubtraction using BigInts\n2n - 1n; // 1n\nYou cannot mix BigInt and number operands in subtraction.\n2n - 1; // TypeError: Cannot mix BigInt and other types, use explicit conversions\n2 - 1n; // TypeError: Cannot mix BigInt and other types, use explicit conversions\nTo do subtraction with a BigInt and a non-BigInt, convert either operand:\n2n - BigInt(1); // 1n\nNumber(2n) - 1; // 1\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-subtraction-operator-minus |", "code_snippets": ["console.log(5 - 3);\n// Expected output: 2\n\nconsole.log(3.5 - 5);\n// Expected output: -1.5\n\nconsole.log(5 - \"hello\");\n// Expected output: NaN\n\nconsole.log(5 - true);\n// Expected output: 4\n", "x - y\n", "5 - 3; // 2\n3 - 5; // -2\n", "\"foo\" - 3; // NaN; \"foo\" is converted to the number NaN\n5 - \"3\"; // 2; \"3\" is converted to the number 3\n", "2n - 1n; // 1n\n", "2n - 1; // TypeError: Cannot mix BigInt and other types, use explicit conversions\n2 - 1n; // TypeError: Cannot mix BigInt and other types, use explicit conversions\n", "2n - BigInt(1); // 1n\nNumber(2n) - 1; // 1\n"], "language": "JavaScript", "source": "mdn", "token_count": 519} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment", "title": "Nullish coalescing assignment (??=)", "content": "Nullish coalescing assignment (??=)\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since September 2020.\nThe nullish coalescing assignment (??=\n) operator, also known as the logical nullish assignment operator, only evaluates the right operand and assigns to the left if the left operand is nullish (null\nor undefined\n).\nTry it\nconst a = { duration: 50 };\na.speed ??= 25;\nconsole.log(a.speed);\n// Expected output: 25\na.duration ??= 10;\nconsole.log(a.duration);\n// Expected output: 50\nSyntax\nx ??= y\nDescription\nNullish coalescing assignment short-circuits, meaning that x ??= y\nis equivalent to x ?? (x = y)\n, except that the expression x\nis only evaluated once.\nNo assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x\nbeing const\n:\nconst x = 1;\nx ??= 2;\nNeither would the following trigger the setter:\nconst x = {\nget value() {\nreturn 1;\n},\nset value(v) {\nconsole.log(\"Setter called\");\n},\n};\nx.value ??= 2;\nIn fact, if x\nis not nullish, y\nis not evaluated at all.\nconst x = 1;\nx ??= console.log(\"y evaluated\");\n// Logs nothing\nExamples\nUsing nullish coalescing assignment\nYou can use the nullish coalescing assignment operator to apply default values to object properties. Compared to using destructuring and default values, ??=\nalso applies the default value if the property has value null\n.\nfunction config(options) {\noptions.duration ??= 100;\noptions.speed ??= 25;\nreturn options;\n}\nconfig({ duration: 125 }); // { duration: 125, speed: 25 }\nconfig({}); // { duration: 100, speed: 25 }\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-assignment-operators |", "code_snippets": ["const a = { duration: 50 };\n\na.speed ??= 25;\nconsole.log(a.speed);\n// Expected output: 25\n\na.duration ??= 10;\nconsole.log(a.duration);\n// Expected output: 50\n", "x ??= y\n", "const x = 1;\nx ??= 2;\n", "const x = {\n get value() {\n return 1;\n },\n set value(v) {\n console.log(\"Setter called\");\n },\n};\n\nx.value ??= 2;\n", "const x = 1;\nx ??= console.log(\"y evaluated\");\n// Logs nothing\n", "function config(options) {\n options.duration ??= 100;\n options.speed ??= 25;\n return options;\n}\n\nconfig({ duration: 125 }); // { duration: 125, speed: 25 }\nconfig({}); // { duration: 100, speed: 25 }\n"], "language": "JavaScript", "source": "mdn", "token_count": 601} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Now/zonedDateTimeISO/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/temporal/now/zoneddatetimeiso/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 42} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatRangeToParts", "title": "Intl.NumberFormat.prototype.formatRangeToParts()", "content": "Intl.NumberFormat.prototype.formatRangeToParts()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since August 2023.\nThe formatRangeToParts()\nmethod of Intl.NumberFormat\ninstances returns an Array\nof objects containing the locale-specific tokens from which it is possible to build custom strings while preserving the locale-specific parts. This makes it possible to provide locale-aware custom formatting ranges of number strings.\nSyntax\nformatRangeToParts(startRange, endRange)\nParameters\nstartRange\n-\nA\nNumber\n,BigInt\n, or string, to format. Strings are parsed in the same way as in number conversion, except thatformatRangeToParts()\nwill use the exact value that the string represents, avoiding loss of precision during implicitly conversion to a number. endRange\nReturn value\nAn Array\nof objects containing the formatted range in parts. Each object has three properties, type\n, value\n, and source\n, each containing a string. The string concatenation of value\n, in the order provided, will result in the same string as formatRange()\n. The type\nmay have the same values as formatToParts()\n, or the additional value \"approximatelySign\"\n(see below). The source\ncan be one of the following:\nstartRange\n-\nThe token is a part of the start number.\nendRange\n-\nThe token is a part of the end number.\n-\nThe token is shared between the start and end; for example, the currency symbol. All literals that are part of the range pattern itself, such as the\n\"\u2013\"\nseparator, are also marked asshared\n.\nIf the start and end numbers are formatted to the same string, then the output has the same list of tokens as calling formatToParts()\non the start number, with all tokens marked as source: \"shared\"\n. In addition, the first token may be an \"approximately equals\" symbol (e.g., \"~\") with type: \"approximatelySign\"\n. The insertion of this symbol only depends on the locale settings, and is inserted even when startRange === endRange\n.\nExceptions\nRangeError\n-\nThrown if either\nstartRange\norendRange\nisNaN\nor an inconvertible string. TypeError\n-\nThrown if either\nstartRange\norendRange\nis undefined.\nExamples\nUsing formatRangeToParts()\nThe formatRange()\nmethod outputs localized, opaque strings that cannot be manipulated directly:\nconst startRange = 3500;\nconst endRange = 9500;\nconst formatter = new Intl.NumberFormat(\"de-DE\", {\nstyle: \"currency\",\ncurrency: \"EUR\",\n});\nconsole.log(formatter.formatRange(startRange, endRange));\n// \"3.500,00\u20139.500,00 \u20ac\"\nHowever, in many user interfaces you may want to customize the formatting of this string, or interleave it with other texts. The formatRangeToParts()\nmethod produces the same information in parts:\nconsole.log(formatter.formatRangeToParts(startRange, endRange));\n// return value:\n[\n{ type: \"integer\", value: \"3\", source: \"startRange\" },\n{ type: \"group\", value: \".\", source: \"startRange\" },\n{ type: \"integer\", value: \"500\", source: \"startRange\" },\n{ type: \"decimal\", value: \",\", source: \"startRange\" },\n{ type: \"fraction\", value: \"00\", source: \"startRange\" },\n{ type: \"literal\", value: \"\u2013\", source: \"shared\" },\n{ type: \"integer\", value: \"9\", source: \"endRange\" },\n{ type: \"group\", value: \".\", source: \"endRange\" },\n{ type: \"integer\", value: \"500\", source: \"endRange\" },\n{ type: \"decimal\", value: \",\", source: \"endRange\" },\n{ type: \"fraction\", value: \"00\", source: \"endRange\" },\n{ type: \"literal\", value: \" \", source: \"shared\" },\n{ type: \"currency\", value: \"\u20ac\", source: \"shared\" },\n];\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # sec-intl.numberformat.prototype.formatrangetoparts |", "code_snippets": ["formatRangeToParts(startRange, endRange)\n", "const startRange = 3500;\nconst endRange = 9500;\n\nconst formatter = new Intl.NumberFormat(\"de-DE\", {\n style: \"currency\",\n currency: \"EUR\",\n});\n\nconsole.log(formatter.formatRange(startRange, endRange));\n// \"3.500,00\u20139.500,00 \u20ac\"\n", "console.log(formatter.formatRangeToParts(startRange, endRange));\n\n// return value:\n[\n { type: \"integer\", value: \"3\", source: \"startRange\" },\n { type: \"group\", value: \".\", source: \"startRange\" },\n { type: \"integer\", value: \"500\", source: \"startRange\" },\n { type: \"decimal\", value: \",\", source: \"startRange\" },\n { type: \"fraction\", value: \"00\", source: \"startRange\" },\n { type: \"literal\", value: \"\u2013\", source: \"shared\" },\n { type: \"integer\", value: \"9\", source: \"endRange\" },\n { type: \"group\", value: \".\", source: \"endRange\" },\n { type: \"integer\", value: \"500\", source: \"endRange\" },\n { type: \"decimal\", value: \",\", source: \"endRange\" },\n { type: \"fraction\", value: \"00\", source: \"endRange\" },\n { type: \"literal\", value: \" \", source: \"shared\" },\n { type: \"currency\", value: \"\u20ac\", source: \"shared\" },\n];\n"], "language": "JavaScript", "source": "mdn", "token_count": 1186} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/toString", "title": "BigInt.prototype.toString()", "content": "BigInt.prototype.toString()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since September 2020.\nThe toString()\nmethod of BigInt\nvalues returns a string representing the specified BigInt\nvalue. The trailing \"n\" is not part of the string.\nTry it\nconsole.log(1024n.toString());\n// Expected output: \"1024\"\nconsole.log(1024n.toString(2));\n// Expected output: \"10000000000\"\nconsole.log(1024n.toString(16));\n// Expected output: \"400\"\nSyntax\ntoString()\ntoString(radix)\nParameters\nradix\nOptional-\nAn integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10.\nReturn value\nA string representing the specified BigInt\nvalue.\nExceptions\nRangeError\n-\nThrown if\nradix\nis less than 2 or greater than 36.\nDescription\nThe BigInt\nobject overrides the toString\nmethod of Object\n; it does not inherit\nObject.prototype.toString()\n. For BigInt\nvalues, the toString()\nmethod returns a string representation of the value in the specified radix.\nFor radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) a\nthrough f\nare used.\nIf the specified BigInt 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 BigInt value preceded by a -\nsign, not the two's complement of the BigInt value.\nThe toString()\nmethod requires its this\nvalue to be a BigInt\nprimitive or wrapper object. It throws a TypeError\nfor other this\nvalues without attempting to coerce them to BigInt values.\nBecause BigInt\ndoesn't have a [Symbol.toPrimitive]()\nmethod, JavaScript calls the toString()\nmethod automatically when a BigInt\nobject is used in a context expecting a string, such as in a template literal. However, BigInt primitive values do not consult the toString()\nmethod to be coerced to strings \u2014 rather, they are directly converted using the same algorithm as the initial toString()\nimplementation.\nBigInt.prototype.toString = () => \"Overridden\";\nconsole.log(`${1n}`); // \"1\"\nconsole.log(`${Object(1n)}`); // \"Overridden\"\nExamples\nUsing toString()\n17n.toString(); // \"17\"\n66n.toString(2); // \"1000010\"\n254n.toString(16); // \"fe\"\n(-10n).toString(2); // \"-1010\"\n(-0xffn).toString(2); // \"-11111111\"\nNegative-zero BigInt\nThere is no negative-zero BigInt\nas there are no negative zeros in integers. -0.0\nis an IEEE floating-point concept that only appears in the JavaScript Number\ntype.\n(-0n).toString(); // \"0\"\nBigInt(-0).toString(); // \"0\"\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-bigint.prototype.tostring |", "code_snippets": ["console.log(1024n.toString());\n// Expected output: \"1024\"\n\nconsole.log(1024n.toString(2));\n// Expected output: \"10000000000\"\n\nconsole.log(1024n.toString(16));\n// Expected output: \"400\"\n", "toString()\ntoString(radix)\n", "BigInt.prototype.toString = () => \"Overridden\";\nconsole.log(`${1n}`); // \"1\"\nconsole.log(`${Object(1n)}`); // \"Overridden\"\n", "17n.toString(); // \"17\"\n66n.toString(2); // \"1000010\"\n254n.toString(16); // \"fe\"\n(-10n).toString(2); // \"-1010\"\n(-0xffn).toString(2); // \"-11111111\"\n", "(-0n).toString(); // \"0\"\nBigInt(-0).toString(); // \"0\"\n"], "language": "JavaScript", "source": "mdn", "token_count": 815} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Reduce_of_empty_array_with_no_initial_value", "title": "TypeError: Reduce of empty array with no initial value", "content": "TypeError: Reduce of empty array with no initial value\nThe JavaScript exception \"reduce of empty array with no initial value\" occurs when a reduce function is used.\nMessage\nTypeError: Reduce of empty array with no initial value (V8-based & Firefox & Safari)\nError type\nTypeError\nWhat went wrong?\nIn JavaScript, there are several reduce functions:\nArray.prototype.reduce()\n,Array.prototype.reduceRight()\nandTypedArray.prototype.reduce()\n,TypedArray.prototype.reduceRight()\n).\nThese functions optionally take an initialValue\n(which will be used as the\nfirst argument to the first call of the callback\n). However, if no initial\nvalue is provided, it will use the first element of the Array\nor\nTypedArray\nas the initial value. This error is raised when an empty array\nis provided because no initial value can be returned in that case.\nExamples\nInvalid cases\nThis problem appears frequently when combined with a filter\n(Array.prototype.filter()\n, TypedArray.prototype.filter()\n)\nwhich will remove all elements of the list. Thus leaving none to be used as the initial\nvalue.\nconst ints = [0, -1, -2, -3, -4, -5];\nints\n.filter((x) => x > 0) // removes all elements\n.reduce((x, y) => x + y); // no more elements to use for the initial value.\nSimilarly, the same issue can happen if there is a typo in a selector, or an unexpected number of elements in a list:\nconst names = document.getElementsByClassName(\"names\");\nconst nameList = Array.prototype.reduce.call(\nnames,\n(acc, name) => `${acc}, ${name}`,\n);\nValid cases\nThese problems can be solved in two different ways.\nOne way is to actually provide an initialValue\nas the neutral element of\nthe operator, such as 0 for the addition, 1 for a multiplication, or an empty string for\na concatenation.\nconst ints = [0, -1, -2, -3, -4, -5];\nints\n.filter((x) => x > 0) // removes all elements\n.reduce((x, y) => x + y, 0); // the initial value is the neutral element of the addition\nAnother way would be to handle the empty case, either before calling\nreduce\n, or in the callback after adding an unexpected dummy initial value.\nconst names = document.getElementsByClassName(\"names\");\nlet nameList1 = \"\";\nif (names.length >= 1) {\nnameList1 = Array.prototype.reduce.call(\nnames,\n(acc, name) => `${acc}, ${name}`,\n);\n}\n// nameList1 === \"\" when names is empty.\nconst nameList2 = Array.prototype.reduce.call(\nnames,\n(acc, name) => {\nif (acc === \"\")\n// initial value\nreturn name;\nreturn `${acc}, ${name}`;\n},\n\"\",\n);\n// nameList2 === \"\" when names is empty.", "code_snippets": ["const ints = [0, -1, -2, -3, -4, -5];\nints\n .filter((x) => x > 0) // removes all elements\n .reduce((x, y) => x + y); // no more elements to use for the initial value.\n", "const names = document.getElementsByClassName(\"names\");\nconst nameList = Array.prototype.reduce.call(\n names,\n (acc, name) => `${acc}, ${name}`,\n);\n", "const ints = [0, -1, -2, -3, -4, -5];\nints\n .filter((x) => x > 0) // removes all elements\n .reduce((x, y) => x + y, 0); // the initial value is the neutral element of the addition\n", "const names = document.getElementsByClassName(\"names\");\n\nlet nameList1 = \"\";\nif (names.length >= 1) {\n nameList1 = Array.prototype.reduce.call(\n names,\n (acc, name) => `${acc}, ${name}`,\n );\n}\n// nameList1 === \"\" when names is empty.\n\nconst nameList2 = Array.prototype.reduce.call(\n names,\n (acc, name) => {\n if (acc === \"\")\n // initial value\n return name;\n return `${acc}, ${name}`;\n },\n \"\",\n);\n// nameList2 === \"\" when names is empty.\n"], "language": "JavaScript", "source": "mdn", "token_count": 863} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Stmt_after_return", "title": "Warning: unreachable code after return statement", "content": "Warning: unreachable code after return statement\nThe JavaScript warning \"unreachable code after return statement\" occurs when using an\nexpression after a return\nstatement, or when using a\nsemicolon-less return statement but including an expression directly after.\nMessage\nWarning: unreachable code after return statement (Firefox)\nError type\nWarning\nWhat went wrong?\nUnreachable code after a return statement might occur in these situations:\n- When using an expression after a\nreturn\nstatement, or - when using a semicolon-less return statement but including an expression directly after.\nWhen an expression exists after a valid return\nstatement, a warning is\ngiven to indicate that the code after the return\nstatement is unreachable,\nmeaning it can never be run.\nWhy should I have semicolons after return\nstatements? In the case of\nsemicolon-less return\nstatements, it can be unclear whether the developer\nintended to return the statement on the following line, or to stop execution and return.\nThe warning indicates that there is ambiguity in the way the return\nstatement is written.\nWarnings will not be shown for semicolon-less returns if these statements follow it:\nExamples\nInvalid cases\nfunction f() {\nlet x = 3;\nx += 4;\nreturn x; // return exits the function immediately\nx -= 3; // so this line will never run; it is unreachable\n}\nfunction g() {\nreturn // this is treated like `return;`\n3 + 4; // so the function returns, and this line is never reached\n}\nValid cases\nfunction f() {\nlet x = 3;\nx += 4;\nx -= 3;\nreturn x; // OK: return after all other statements\n}\nfunction g() {\nreturn 3 + 4 // OK: semicolon-less return with expression on the same line\n}", "code_snippets": ["function f() {\n let x = 3;\n x += 4;\n return x; // return exits the function immediately\n x -= 3; // so this line will never run; it is unreachable\n}\n\nfunction g() {\n return // this is treated like `return;`\n 3 + 4; // so the function returns, and this line is never reached\n}\n", "function f() {\n let x = 3;\n x += 4;\n x -= 3;\n return x; // OK: return after all other statements\n}\n\nfunction g() {\n return 3 + 4 // OK: semicolon-less return with expression on the same line\n}\n"], "language": "JavaScript", "source": "mdn", "token_count": 538} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/resolvedOptions", "title": "Intl.Collator.prototype.resolvedOptions()", "content": "Intl.Collator.prototype.resolvedOptions()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since September 2017.\nThe resolvedOptions()\nmethod of Intl.Collator\ninstances returns a new object with properties reflecting the options computed during initialization of this Collator\nobject.\nTry it\nconst numberDe = new Intl.NumberFormat(\"de-DE\");\nconst numberAr = new Intl.NumberFormat(\"ar\");\nconsole.log(numberDe.resolvedOptions().numberingSystem);\n// Expected output: \"latn\"\nconsole.log(numberAr.resolvedOptions().numberingSystem);\n// Expected output: \"arab\"\nSyntax\nresolvedOptions()\nParameters\nNone.\nReturn value\nA new object with properties reflecting the options computed during the initialization of this Collator\nobject. The object has the following properties, in the order they are listed:\nlocale\n-\nThe BCP 47 language tag for the locale actually used, determined by the locale negotiation process. Only the\nco\n,kn\n, andkf\nUnicode extension keys, if requested and supported, may be included in the output. usage\n-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is either\"sort\"\nor\"search\"\n. The default is\"sort\"\n. sensitivity\n-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is either\"base\"\n,\"accent\"\n,\"case\"\n, or\"variant\"\n. The default is\"variant\"\nfor usage\"sort\"\n; it's locale dependent for usage\"search\"\n. ignorePunctuation\n-\nThe value provided for this property in the\noptions\nargument, with default filled in as needed. It is a boolean. The default istrue\nfor Thai (th\n) andfalse\nfor all other languages. collation\n-\nThe value provided for this property in the\noptions\nargument, or using the Unicode extension key\"co\"\n, with default filled in as needed. It is a supported collation type for this locale. The default is\"default\"\n. numeric\n-\nThe value provided for this property in the\noptions\nargument, or using the Unicode extension key\"kn\"\n, with default filled in as needed. It is a boolean. The default isfalse\n. If the implementation does not support this Unicode extension key, this property is omitted. caseFirst\n-\nThe value provided for this property in the\noptions\nargument, or using the Unicode extension key\"kf\"\n, with default filled in as needed. It is either\"upper\"\n,\"lower\"\n, or\"false\"\n. The default is\"false\"\n. If the implementation does not support this Unicode extension key, this property is omitted.\nExamples\nUsing the resolvedOptions method\nconst de = new Intl.Collator(\"de\", { sensitivity: \"base\" });\nconst usedOptions = de.resolvedOptions();\nusedOptions.locale; // \"de\"\nusedOptions.usage; // \"sort\"\nusedOptions.sensitivity; // \"base\"\nusedOptions.ignorePunctuation; // false\nusedOptions.collation; // \"default\"\nusedOptions.numeric; // false\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # sec-intl.collator.prototype.resolvedoptions |", "code_snippets": ["const numberDe = new Intl.NumberFormat(\"de-DE\");\nconst numberAr = new Intl.NumberFormat(\"ar\");\n\nconsole.log(numberDe.resolvedOptions().numberingSystem);\n// Expected output: \"latn\"\n\nconsole.log(numberAr.resolvedOptions().numberingSystem);\n// Expected output: \"arab\"\n", "resolvedOptions()\n", "const de = new Intl.Collator(\"de\", { sensitivity: \"base\" });\nconst usedOptions = de.resolvedOptions();\n\nusedOptions.locale; // \"de\"\nusedOptions.usage; // \"sort\"\nusedOptions.sensitivity; // \"base\"\nusedOptions.ignorePunctuation; // false\nusedOptions.collation; // \"default\"\nusedOptions.numeric; // false\n"], "language": "JavaScript", "source": "mdn", "token_count": 899} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/function/name/index.md\n\n# Original Wiki contributors\nmfuji09\nwbamberg\nfscholz\nbenaston\nnakhodkiin\nihanson\nvinyldarkscratch\nYialo\nrkoeninger\nyg448\nsnuggs\npmdartus\nSheppy\nchristophe.hurpeau\nminstrel1977\njameshkramer\nVelenir\nZeroUnderscoreOu\ndavid_ross\ndarrenburgess\nnmve\nkdex\nabout-code\nxfq\nmata007\njleedev\njpmedley\nreecehudson\nbergus\nfastest963\nMingun\nQantas94Heavy\nethertank\nziyunfei\nfasttime\nevilpie\nSevenspade\nNickolay\nAndrea@3site.it\nSeant23\nAndreas Wuest\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 147} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length", "title": "String: length", "content": "String: length\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe length\ndata property of a String\nvalue contains the length of the string in UTF-16 code units.\nTry it\nconst str = \"Life, the universe and everything. Answer:\";\nconsole.log(`${str} ${str.length}`);\n// Expected output: \"Life, the universe and everything. Answer: 42\"\nValue\nA non-negative integer.\nProperty attributes of String: length | |\n|---|---|\n| Writable | no |\n| Enumerable | no |\n| Configurable | no |\nDescription\nThis property returns the number of code units in the string. JavaScript uses UTF-16 encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by length\nto not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, mathematical symbols, or obscure Chinese characters, you may need to account for the difference between code units and characters.\nThe language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for precise integers. However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer.\n- In V8 (used by Chrome and Node), the maximum length is 229 - 24 (~1GiB). On 32-bit systems, the maximum length is 228 - 16 (~512MiB).\n- In Firefox, the maximum length is 230 - 2 (~2GiB). Before Firefox 65, the maximum length was 228 - 1 (~512MiB).\n- In Safari, the maximum length is 231 - 1 (~4GiB).\nIf you are working with large strings in other encodings (such as UTF-8 files or blobs), note that when you load the data into a JS string, the encoding always becomes UTF-16. The size of the string may be different from the size of the source file.\nconst str1 = \"a\".repeat(2 ** 29 - 24); // Success\nconst str2 = \"a\".repeat(2 ** 29 - 23); // RangeError: Invalid string length\nconst buffer = new Uint8Array(2 ** 29 - 24).fill(\"a\".codePointAt(0)); // This buffer is 512MiB in size\nconst str = new TextDecoder().decode(buffer); // This string is 1GiB in size\nFor an empty string, length\nis 0.\nThe static property String.length\nis unrelated to the length of strings. It's the arity of the String\nfunction (loosely, the number of formal parameters it has), which is 1.\nSince length\ncounts code units instead of characters, if you want to get the number of characters, you can first split the string with its iterator, which iterates by characters:\nfunction getCharacterLength(str) {\n// The string iterator that is used here iterates over characters,\n// not mere code units\nreturn [...str].length;\n}\nconsole.log(getCharacterLength(\"A\\uD87E\\uDC04Z\")); // 3\nIf you want to count characters by grapheme clusters, use Intl.Segmenter\n. You can first pass the string you want to split to the segment()\nmethod, and then iterate over the returned Segments\nobject to get the length:\nfunction getGraphemeCount(str) {\nconst segmenter = new Intl.Segmenter(\"en-US\", { granularity: \"grapheme\" });\n// The Segments object iterator that is used here iterates over characters in grapheme clusters,\n// which may consist of multiple Unicode characters\nreturn [...segmenter.segment(str)].length;\n}\nconsole.log(getGraphemeCount(\"\ud83d\udc68\ud83d\udc69\ud83d\udc67\ud83d\udc67\")); // 1\nExamples\nBasic usage\nconst x = \"Mozilla\";\nconst empty = \"\";\nconsole.log(`${x} is ${x.length} code units long`);\n// Mozilla is 7 code units long\nconsole.log(`The empty string has a length of ${empty.length}`);\n// The empty string has a length of 0\nStrings with length not equal to the number of characters\nconst emoji = \"\ud83d\ude04\";\nconsole.log(emoji.length); // 2\nconsole.log([...emoji].length); // 1\nconst adlam = \"\ud83a\udd32\ud83a\udd4b\ud83a\udd23\ud83a\udd2b\";\nconsole.log(adlam.length); // 8\nconsole.log([...adlam].length); // 4\nconst formula = \"\u2200\ud835\udc65\u2208\u211d,\ud835\udc65\u00b2\u22650\";\nconsole.log(formula.length); // 11\nconsole.log([...formula].length); // 9\nAssigning to length\nBecause string is a primitive, attempting to assign a value to a string's length\nproperty has no observable effect, and will throw in strict mode.\nconst myString = \"bluebells\";\nmyString.length = 4;\nconsole.log(myString); // \"bluebells\"\nconsole.log(myString.length); // 9\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-properties-of-string-instances-length |", "code_snippets": ["const str = \"Life, the universe and everything. Answer:\";\n\nconsole.log(`${str} ${str.length}`);\n// Expected output: \"Life, the universe and everything. Answer: 42\"\n", "const str1 = \"a\".repeat(2 ** 29 - 24); // Success\nconst str2 = \"a\".repeat(2 ** 29 - 23); // RangeError: Invalid string length\n\nconst buffer = new Uint8Array(2 ** 29 - 24).fill(\"a\".codePointAt(0)); // This buffer is 512MiB in size\nconst str = new TextDecoder().decode(buffer); // This string is 1GiB in size\n", "function getCharacterLength(str) {\n // The string iterator that is used here iterates over characters,\n // not mere code units\n return [...str].length;\n}\n\nconsole.log(getCharacterLength(\"A\\uD87E\\uDC04Z\")); // 3\n", "function getGraphemeCount(str) {\n const segmenter = new Intl.Segmenter(\"en-US\", { granularity: \"grapheme\" });\n // The Segments object iterator that is used here iterates over characters in grapheme clusters,\n // which may consist of multiple Unicode characters\n return [...segmenter.segment(str)].length;\n}\n\nconsole.log(getGraphemeCount(\"\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d\udc67\")); // 1\n", "const x = \"Mozilla\";\nconst empty = \"\";\n\nconsole.log(`${x} is ${x.length} code units long`);\n// Mozilla is 7 code units long\n\nconsole.log(`The empty string has a length of ${empty.length}`);\n// The empty string has a length of 0\n", "const emoji = \"\ud83d\ude04\";\nconsole.log(emoji.length); // 2\nconsole.log([...emoji].length); // 1\nconst adlam = \"\ud83a\udd32\ud83a\udd4b\ud83a\udd23\ud83a\udd2b\";\nconsole.log(adlam.length); // 8\nconsole.log([...adlam].length); // 4\nconst formula = \"\u2200\ud835\udc65\u2208\u211d,\ud835\udc65\u00b2\u22650\";\nconsole.log(formula.length); // 11\nconsole.log([...formula].length); // 9\n", "const myString = \"bluebells\";\n\nmyString.length = 4;\nconsole.log(myString); // \"bluebells\"\nconsole.log(myString.length); // 9\n"], "language": "JavaScript", "source": "mdn", "token_count": 1564} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/valueOf/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/string/valueof/index.md\n\n# Original Wiki contributors\nfscholz\nwbamberg\nchrisdavidmills\njameshkramer\neduardoboucas\nMingun\nSheppy\nevilpie\nMgjbot\nDiablownik\nMaian\nDria\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 73} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toLocaleString/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/object/tolocalestring/index.md\n\n# Original Wiki contributors\nmfuji09\nchrisdavidmills\nfscholz\nalattalatta\nstmoreau\nwbamberg\njameshkramer\neduardoboucas\nmhubenthal\nMingun\nSheppy\nNorbert\nethertank\nYuichirou\nPtak82\nNickolay\nMaian\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 88} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/String", "title": "String() constructor", "content": "String() constructor\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe String()\nconstructor creates String\nobjects. When called as a function, it returns primitive values of type String.\nSyntax\nnew String(thing)\nString(thing)\nNote:\nString()\ncan be called with or without new\n, but with different effects. See Return value.\nParameters\nthing\n-\nAnything to be converted to a string.\nReturn value\nWhen String()\nis called as a function (without new\n), it returns value\ncoerced to a string primitive. Specially, Symbol values are converted to \"Symbol(description)\"\n, where description\nis the description of the Symbol, instead of throwing.\nWhen String()\nis called as a constructor (with new\n), it coerces value\nto a string primitive (without special symbol handling) and returns a wrapping String\nobject, which is not a primitive.\nWarning:\nYou should rarely find yourself using String\nas a constructor.\nExamples\nString constructor and String function\nString function and String constructor produce different results:\nconst a = new String(\"Hello world\"); // a === \"Hello world\" is false\nconst b = String(\"Hello world\"); // b === \"Hello world\" is true\na instanceof String; // is true\nb instanceof String; // is false\ntypeof a; // \"object\"\ntypeof b; // \"string\"\nHere, the function produces a string (the primitive type) as promised. However, the constructor produces an instance of the type String (an object wrapper) and that's why you rarely want to use the String constructor at all.\nUsing String() to stringify a symbol\nString()\nis the only case where a symbol can be converted to a string without throwing, because it's very explicit.\nconst sym = Symbol(\"example\");\n`${sym}`; // TypeError: Cannot convert a Symbol value to a string\n\"\" + sym; // TypeError: Cannot convert a Symbol value to a string\n\"\".concat(sym); // TypeError: Cannot convert a Symbol value to a string\nconst sym = Symbol(\"example\");\nString(sym); // \"Symbol(example)\"\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-string-constructor |\nBrowser compatibility\nSee also\n- Numbers and strings guide", "code_snippets": ["new String(thing)\nString(thing)\n", "const a = new String(\"Hello world\"); // a === \"Hello world\" is false\nconst b = String(\"Hello world\"); // b === \"Hello world\" is true\na instanceof String; // is true\nb instanceof String; // is false\ntypeof a; // \"object\"\ntypeof b; // \"string\"\n", "const sym = Symbol(\"example\");\n`${sym}`; // TypeError: Cannot convert a Symbol value to a string\n\"\" + sym; // TypeError: Cannot convert a Symbol value to a string\n\"\".concat(sym); // TypeError: Cannot convert a Symbol value to a string\n", "const sym = Symbol(\"example\");\nString(sym); // \"Symbol(example)\"\n"], "language": "JavaScript", "source": "mdn", "token_count": 697} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/rawJSON", "title": "JSON.rawJSON()", "content": "JSON.rawJSON()\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe JSON.rawJSON()\nstatic method creates a \"raw JSON\" object containing a piece of JSON text. When serialized to JSON, the raw JSON object is treated as if it is already a piece of JSON. This text is required to be valid JSON.\nSyntax\nJSON.rawJSON(string)\nParameters\nstring\n-\nThe JSON text. Must be valid JSON representing a primitive value.\nReturn value\nAn object that can be used to create JSON text with the exact same content as the string\nprovided, without quotes around the string itself. This object has null\nprototype and is frozen (so it never gets accidentally serialized as a regular object by any kind of primitive conversion), and the following property:\nrawJSON\n-\nThe original JSON\nstring\nprovided.\nFurthermore, it has a private field that marks itself as a raw JSON object. This allows it to be identified by JSON.stringify()\nand JSON.isRawJSON()\n.\nExceptions\nSyntaxError\n-\nThrown if the\nstring\nis not valid JSON, or if it represents an object or array.\nDescription\nA raw JSON object can be seen as an immutable, atomic data structure like any kind of primitive. It is not a regular object and it contains no data other than the raw JSON text. It is used to \"pre-serialize\" data to formats that JSON.stringify\nitself cannot produce for various reasons. The most typical use case is the floating point number loss of precision problem. For example:\nJSON.stringify({ value: 12345678901234567890 });\n// {\"value\":12345678901234567000}\nThe value is not exactly equivalent to the original number any more! This is because JavaScript uses floating point representation for all numbers, so it cannot represent all integers exactly. The number literal 12345678901234567890\nitself is already rounded to the nearest representable number when it is parsed by JavaScript.\nWithout JSON.rawJSON\n, there is no way to tell JSON.stringify\nto produce the number literal 12345678901234567890\n, because there is simply no corresponding JavaScript number value. With raw JSON, you can directly tell JSON.stringify()\nwhat a particular value should be stringified as:\nconst rawJSON = JSON.rawJSON(\"12345678901234567890\");\nJSON.stringify({ value: rawJSON });\n// {\"value\":12345678901234567890}\nFor a more complete example of this, see Lossless number serialization.\nNote that although we passed a string to JSON.rawJSON()\n, it still becomes a number in the final JSON. This is because the string represents the verbatim JSON text. If you want to serialize a string, you should use JSON.rawJSON()\nwith a quotes-enclosed string value:\nconst rawJSON = JSON.rawJSON('\"Hello world\"');\nJSON.stringify({ value: rawJSON });\n// {\"value\":\"Hello world\"}\nJSON.rawJSON\nallows you to insert arbitrary JSON text, but does not allow you to create invalid JSON. Anything that was not permitted by the JSON syntax is not permitted by JSON.rawJSON()\neither:\nconst rawJSON = JSON.rawJSON('\"Hello\\nworld\"'); // Syntax error, because line breaks are not allowed in JSON strings\nFurthermore, you cannot use JSON.rawJSON()\nto create JSON objects or arrays.\nExamples\nUsing JSON.rawJSON() to create JSON expressions of different types\nconst numJSON = JSON.rawJSON(\"123\");\nconst strJSON = JSON.rawJSON('\"Hello world\"');\nconst boolJSON = JSON.rawJSON(\"true\");\nconst nullJSON = JSON.rawJSON(\"null\");\nconsole.log(\nJSON.stringify({\nage: numJSON,\nmessage: strJSON,\nisActive: boolJSON,\nnothing: nullJSON,\n}),\n);\n// {\"age\":123,\"message\":\"Hello world\",\"isActive\":true,\"nothing\":null}\nHowever, you cannot use JSON.rawJSON()\nto create JSON objects or arrays:\nconst arrJSON = JSON.rawJSON(\"[1, 2, 3]\");\nconst objJSON = JSON.rawJSON('{\"a\": 1, \"b\": 2}');\n// SyntaxError\nUsing JSON.rawJSON() to create escaped string literals\nApart from numbers, there is only one other type that does not have a one-to-one correspondence between JavaScript values and JSON text: strings. When strings are serialized to JSON, all code points, other than those that are not legal inside JSON string literals (such as line breaks), are printed literally:\nconsole.log(JSON.stringify({ value: \"\\ud83d\\ude04\" })); // {\"value\":\"\ud83d\ude04\"}\nThis may not be desirable, because the receiver of this string may handle Unicode differently. To improve interoperability, you can explicitly specify the string to be serialized with escape sequences:\nconst rawJSON = JSON.rawJSON('\"\\\\ud83d\\\\ude04\"');\nconst objStr = JSON.stringify({ value: rawJSON });\nconsole.log(objStr); // {\"value\":\"\\ud83d\\ude04\"}\nconsole.log(JSON.parse(objStr).value); // \ud83d\ude04\nNote that the double backslashes in the rawJSON\nactually represents a single slash character.\nSpecifications\n| Specification |\n|---|\n| JSON.parse source text access # sec-json.rawjson |", "code_snippets": ["JSON.rawJSON(string)\n", "JSON.stringify({ value: 12345678901234567890 });\n// {\"value\":12345678901234567000}\n", "const rawJSON = JSON.rawJSON(\"12345678901234567890\");\nJSON.stringify({ value: rawJSON });\n// {\"value\":12345678901234567890}\n", "const rawJSON = JSON.rawJSON('\"Hello world\"');\nJSON.stringify({ value: rawJSON });\n// {\"value\":\"Hello world\"}\n", "const rawJSON = JSON.rawJSON('\"Hello\\nworld\"'); // Syntax error, because line breaks are not allowed in JSON strings\n", "const numJSON = JSON.rawJSON(\"123\");\nconst strJSON = JSON.rawJSON('\"Hello world\"');\nconst boolJSON = JSON.rawJSON(\"true\");\nconst nullJSON = JSON.rawJSON(\"null\");\n\nconsole.log(\n JSON.stringify({\n age: numJSON,\n message: strJSON,\n isActive: boolJSON,\n nothing: nullJSON,\n }),\n);\n\n// {\"age\":123,\"message\":\"Hello world\",\"isActive\":true,\"nothing\":null}\n", "const arrJSON = JSON.rawJSON(\"[1, 2, 3]\");\nconst objJSON = JSON.rawJSON('{\"a\": 1, \"b\": 2}');\n// SyntaxError\n", "console.log(JSON.stringify({ value: \"\\ud83d\\ude04\" })); // {\"value\":\"\ud83d\ude04\"}\n", "const rawJSON = JSON.rawJSON('\"\\\\ud83d\\\\ude04\"');\nconst objStr = JSON.stringify({ value: rawJSON });\nconsole.log(objStr); // {\"value\":\"\\ud83d\\ude04\"}\nconsole.log(JSON.parse(objStr).value); // \ud83d\ude04\n"], "language": "JavaScript", "source": "mdn", "token_count": 1490} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/operators/nullish_coalescing_assignment/index.md\n\n# Original Wiki contributors\nhinell\njridgewell\nfscholz\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 54} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/date/valueof/index.md\n\n# Original Wiki contributors\nmfuji09\nfscholz\nschalkneethling\njameshkramer\neduardoboucas\nMingun\nethertank\nSheppy\nevilpie\nPtak82\nMaian\nDria\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 72} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/formatToParts/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/listformat/formattoparts/index.md\n\n# Original Wiki contributors\nwbamberg\nfscholz\nSphinxKnight\nrwe2020\nsideshowbarker\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 62} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder_assignment", "title": "Remainder assignment (%=)", "content": "Remainder assignment (%=)\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe remainder assignment (%=\n) operator performs remainder on the two operands and assigns the result to the left operand.\nTry it\nlet a = 3;\nconsole.log((a %= 2));\n// Expected output: 1\nconsole.log((a %= 0));\n// Expected output: NaN\nconsole.log((a %= \"hello\"));\n// Expected output: NaN\nSyntax\njs\nx %= y\nDescription\nx %= y\nis equivalent to x = x % y\n, except that the expression x\nis only evaluated once.\nExamples\nUsing remainder assignment\njs\nlet bar = 5;\nbar %= 2; // 1\nbar %= \"foo\"; // NaN\nbar %= 0; // NaN\nlet foo = 3n;\nfoo %= 2n; // 1n\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-assignment-operators |", "code_snippets": ["let a = 3;\n\nconsole.log((a %= 2));\n// Expected output: 1\n\nconsole.log((a %= 0));\n// Expected output: NaN\n\nconsole.log((a %= \"hello\"));\n// Expected output: NaN\n", "x %= y\n", "let bar = 5;\n\nbar %= 2; // 1\nbar %= \"foo\"; // NaN\nbar %= 0; // NaN\n\nlet foo = 3n;\nfoo %= 2n; // 1n\n"], "language": "JavaScript", "source": "mdn", "token_count": 276} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Called_on_incompatible_type/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/errors/called_on_incompatible_type/index.md\n\n# Original Wiki contributors\nfscholz\nSphinxKnight\nth0rgall\nPatrickKettner\nWangNianyi2001\nnbp\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 63} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Now/plainTimeISO/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/temporal/now/plaintimeiso/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 41} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Duration/hours", "title": "Temporal.Duration.prototype.hours", "content": "Temporal.Duration.prototype.hours\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe hours\naccessor property of Temporal.Duration\ninstances returns an integer representing the number of hours in the duration.\nUnless the duration is balanced, you cannot assume the range of this value, but you can know its sign by checking the duration's sign\nproperty. If it is balanced to a unit above hours, the hours\nabsolute value will be between 0 and 23, inclusive.\nThe set accessor of hours\nis undefined\n. You cannot change this property directly. Use the with()\nmethod to create a new Temporal.Duration\nobject with the desired new value.\nExamples\nUsing hours\njs\nconst d1 = Temporal.Duration.from({ hours: 1, minutes: 30 });\nconst d2 = Temporal.Duration.from({ hours: -1, minutes: -30 });\nconst d3 = Temporal.Duration.from({ days: 1 });\nconst d4 = Temporal.Duration.from({ hours: 24 });\nconsole.log(d1.hours); // 1\nconsole.log(d2.hours); // -1\nconsole.log(d3.hours); // 0\nconsole.log(d4.hours); // 24\n// Balance d4\nconst d4Balanced = d4.round({ largestUnit: \"days\" });\nconsole.log(d4Balanced.hours); // 0\nconsole.log(d4Balanced.days); // 1\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-get-temporal.duration.prototype.hours |\nBrowser compatibility\nSee also\nTemporal.Duration\nTemporal.Duration.prototype.years\nTemporal.Duration.prototype.months\nTemporal.Duration.prototype.weeks\nTemporal.Duration.prototype.days\nTemporal.Duration.prototype.minutes\nTemporal.Duration.prototype.seconds\nTemporal.Duration.prototype.milliseconds\nTemporal.Duration.prototype.microseconds\nTemporal.Duration.prototype.nanoseconds", "code_snippets": ["const d1 = Temporal.Duration.from({ hours: 1, minutes: 30 });\nconst d2 = Temporal.Duration.from({ hours: -1, minutes: -30 });\nconst d3 = Temporal.Duration.from({ days: 1 });\nconst d4 = Temporal.Duration.from({ hours: 24 });\n\nconsole.log(d1.hours); // 1\nconsole.log(d2.hours); // -1\nconsole.log(d3.hours); // 0\nconsole.log(d4.hours); // 24\n\n// Balance d4\nconst d4Balanced = d4.round({ largestUnit: \"days\" });\nconsole.log(d4Balanced.hours); // 0\nconsole.log(d4Balanced.days); // 1\n"], "language": "JavaScript", "source": "mdn", "token_count": 538} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Already_has_pragma", "title": "Warning: -file- is being assigned a //# sourceMappingURL, but already has one", "content": "Warning: -file- is being assigned a //# sourceMappingURL, but already has one\nThe JavaScript warning \"-file- is being assigned a //# sourceMappingURL, but already has one.\" occurs when a source map has been specified more than once for a given JavaScript source.\nMessage\nWarning: -file- is being assigned a //# sourceMappingURL, but already has one.\nError type\nA warning. JavaScript execution won't be halted.\nWhat went wrong?\nA source map has been specified more than once for a given JavaScript source.\nJavaScript sources are often combined and minified to make delivering them from the server more efficient. With source maps, the debugger can map the code being executed to the original source files. There are two ways to assign a source map, either by using a comment or by setting a header to the JavaScript file.\nExamples\nSetting source maps\nSetting a source map by using a comment in the file:\njs\n//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map\nOr, alternatively, you can set a header to your JavaScript file:\nhttp\nX-SourceMap: /path/to/file.js.map\nSee also\n- Use a source map in the Firefox source docs\n- Introduction to JavaScript source maps on developer.chrome.com (2012)", "code_snippets": ["//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map\n", "X-SourceMap: /path/to/file.js.map\n"], "language": "JavaScript", "source": "mdn", "token_count": 326} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/toLocaleString/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/bigint/tolocalestring/index.md\n\n# Original Wiki contributors\nwbamberg\nfscholz\nchrisdavidmills\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 55} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors", "title": "Property accessors", "content": "Property accessors\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nProperty accessors provide access to an object's properties by using the dot notation or the bracket notation.\nTry it\nconst person1 = {};\nperson1[\"firstName\"] = \"Mario\";\nperson1[\"lastName\"] = \"Rossi\";\nconsole.log(person1.firstName);\n// Expected output: \"Mario\"\nconst person2 = {\nfirstName: \"John\",\nlastName: \"Doe\",\n};\nconsole.log(person2[\"lastName\"]);\n// Expected output: \"Doe\"\nSyntax\nobject.propertyName\nobject[expression]\nobject.#privateProperty\nDescription\nOne can think of an object as an associative array (a.k.a. map, dictionary, hash, lookup table). The keys in this array are the names of the object's properties.\nThere are two ways to access properties: dot notation and bracket notation.\nDot notation\nIn the object.propertyName\nsyntax, the propertyName\nmust be a valid JavaScript identifier which can also be a reserved word. For example, object.$1\nis valid, while object.1\nis not.\nconst variable = object.propertyName;\nobject.propertyName = value;\nconst object = {};\nobject.$1 = \"foo\";\nconsole.log(object.$1); // 'foo'\nconst object = {};\nobject.1 = \"bar\"; // SyntaxError\nconsole.log(object.1); // SyntaxError\nHere, the method named createElement\nis retrieved from document\nand is called.\ndocument.createElement(\"pre\");\nIf you use a method for a numeric literal, and the numeric literal has no exponent and no decimal point, you should leave white-space(s) before the dot preceding the method call, so that the dot is not interpreted as a decimal point.\n77 .toExponential();\n// or\n77\n.toExponential();\n// or\n(77).toExponential();\n// or\n77..toExponential();\n// or\n77.0.toExponential();\n// because 77. === 77.0, no ambiguity\nIn addition, private elements can only be accessed using dot notation within the class that defines them.\nBracket notation\nIn the object[expression]\nsyntax, the expression\nshould evaluate to a string or Symbol that represents the property's name. So, it can be any string literal, for example, including '1foo'\n, '!bar!'\n, or even ' '\n(a space).\nconst variable = object[propertyName];\nobject[propertyName] = value;\nThis does the exact same thing as the previous example.\ndocument[\"createElement\"](\"pre\");\nA space before bracket notation is allowed.\ndocument [\"createElement\"](\"pre\");\nPassing expressions that evaluate to property name will do the same thing as directly passing the property name.\nconst key = \"name\";\nconst getKey = () => \"name\";\nconst Obj = { name: \"Michel\" };\nObj[\"name\"]; // returns \"Michel\"\nObj[key]; // evaluates to Obj[\"name\"], and returns \"Michel\"\nObj[getKey()]; // evaluates to Obj[\"name\"], and returns \"Michel\"\nHowever, beware of using square brackets to access properties whose names are given by external input. This may make your code susceptible to object injection attacks.\nProperty names\nEach property name is a string or a Symbol. Any other value, including a number, is coerced to a string. This outputs 'value'\n, since 1\nis coerced into '1'\n.\nconst object = {};\nobject[\"1\"] = \"value\";\nconsole.log(object[1]);\nThis also outputs 'value'\n, since both foo\nand bar\nare converted to the same string (\"[object Object]\"\n).\nconst foo = { uniqueProp: 1 };\nconst bar = { uniqueProp: 2 };\nconst object = {};\nobject[foo] = \"value\";\nconsole.log(object[bar]);\nMethod binding\nIt's typical when speaking of an object's properties to make a distinction between properties and methods. However, the property/method distinction is little more than a convention. A method is a property that can be called (for example, if it has a reference to a Function\ninstance as its value).\nA method is not bound to the object that it is a property of. Specifically, this\nis not fixed in a method and does not necessarily refer to the object containing the method. Instead, this\nis \"passed\" by the function call. See the reference for this\n.\nExamples\nBracket notation vs. eval()\nJavaScript novices often make the mistake of using eval()\nwhere the bracket notation can be used instead.\nFor example, the following syntax is often seen in many scripts.\nconst x = eval(`document.forms.form_name.elements.${strFormControl}.value`);\neval()\nis slow and should be avoided whenever possible. Also, strFormControl\nwould have to hold an identifier, which is not required for names and id\ns of form controls. It is better to use bracket notation instead:\nconst x = document.forms.form_name.elements[strFormControl].value;\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-property-accessors |", "code_snippets": ["const person1 = {};\nperson1[\"firstName\"] = \"Mario\";\nperson1[\"lastName\"] = \"Rossi\";\n\nconsole.log(person1.firstName);\n// Expected output: \"Mario\"\n\nconst person2 = {\n firstName: \"John\",\n lastName: \"Doe\",\n};\n\nconsole.log(person2[\"lastName\"]);\n// Expected output: \"Doe\"\n", "object.propertyName\nobject[expression]\nobject.#privateProperty\n", "const variable = object.propertyName;\nobject.propertyName = value;\n", "const object = {};\nobject.$1 = \"foo\";\nconsole.log(object.$1); // 'foo'\n", "const object = {};\nobject.1 = \"bar\"; // SyntaxError\nconsole.log(object.1); // SyntaxError\n", "document.createElement(\"pre\");\n", "77 .toExponential();\n// or\n77\n.toExponential();\n// or\n(77).toExponential();\n// or\n77..toExponential();\n// or\n77.0.toExponential();\n// because 77. === 77.0, no ambiguity\n", "const variable = object[propertyName];\nobject[propertyName] = value;\n", "document[\"createElement\"](\"pre\");\n", "document [\"createElement\"](\"pre\");\n", "const key = \"name\";\nconst getKey = () => \"name\";\nconst Obj = { name: \"Michel\" };\n\nObj[\"name\"]; // returns \"Michel\"\nObj[key]; // evaluates to Obj[\"name\"], and returns \"Michel\"\nObj[getKey()]; // evaluates to Obj[\"name\"], and returns \"Michel\"\n", "const object = {};\nobject[\"1\"] = \"value\";\nconsole.log(object[1]);\n", "const foo = { uniqueProp: 1 };\nconst bar = { uniqueProp: 2 };\nconst object = {};\nobject[foo] = \"value\";\nconsole.log(object[bar]);\n", "const x = eval(`document.forms.form_name.elements.${strFormControl}.value`);\n", "const x = document.forms.form_name.elements[strFormControl].value;\n"], "language": "JavaScript", "source": "mdn", "token_count": 1527} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Stmt_after_return/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/errors/stmt_after_return/index.md\n\n# Original Wiki contributors\nfscholz\nyhakina1114\nrolfedh\njorendorff-moz\nclarkbdubya\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 58} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Symbol.hasInstance/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/function/symbol.hasinstance/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 41} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Duration/weeks/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/temporal/duration/weeks/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 40} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/formatToParts/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/durationformat/formattoparts/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 43} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toLocaleString", "title": "Object.prototype.toLocaleString()", "content": "Object.prototype.toLocaleString()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe toLocaleString()\nmethod of Object\ninstances returns a string representing this object. This method is meant to be overridden by derived objects for locale-specific purposes.\nTry it\nconst date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\nconsole.log(date.toLocaleString(\"ar-EG\"));\n// Expected output: \"\u0662\u0660/\u0661\u0662/\u0662\u0660\u0661\u0662 \u0664:\u0660\u0660:\u0660\u0660 \u0635\"\nconst number = 123456.789;\nconsole.log(number.toLocaleString(\"de-DE\"));\n// Expected output: \"123.456,789\"\nSyntax\ntoLocaleString()\nParameters\nNone. However, all objects that override this method are expected to accept at most two parameters, corresponding to locales\nand options\n, such as Number.prototype.toLocaleString\n. The parameter positions should not be used for any other purpose.\nReturn value\nThe return value of calling this.toString()\n.\nDescription\nAll objects that inherit from Object.prototype\n(that is, all except null\n-prototype objects) inherit the toLocaleString()\nmethod. Object\n's toLocaleString\nreturns the result of calling this.toString()\n.\nThis function is provided to give objects a generic toLocaleString\nmethod, even though not all may use it. In the core language, these built-in objects override toLocaleString\nto provide locale-specific formatting:\nExamples\nUsing the base toLocaleString() method\nThe base toLocaleString()\nmethod simply calls toString()\n.\nconst obj = {\ntoString() {\nreturn \"My Object\";\n},\n};\nconsole.log(obj.toLocaleString()); // \"My Object\"\nArray toLocaleString() override\nArray.prototype.toLocaleString()\nis used to print array values as a string by invoking each element's toLocaleString()\nmethod and joining the results with a locale-specific separator. For example:\nconst testArray = [4, 7, 10];\nconst euroPrices = testArray.toLocaleString(\"fr\", {\nstyle: \"currency\",\ncurrency: \"EUR\",\n});\n// \"4,00 \u20ac,7,00 \u20ac,10,00 \u20ac\"\nDate toLocaleString() override\nDate.prototype.toLocaleString()\nis used to print out date displays more suitable for specific locales. For example:\nconst testDate = new Date();\n// \"Fri May 29 2020 18:04:24 GMT+0100 (British Summer Time)\"\nconst deDate = testDate.toLocaleString(\"de\");\n// \"29.5.2020, 18:04:24\"\nconst frDate = testDate.toLocaleString(\"fr\");\n// \"29/05/2020, 18:04:24\"\nNumber toLocaleString() override\nNumber.prototype.toLocaleString()\nis used to print out number displays more suitable for specific locales, e.g., with the correct separators. For example:\nconst testNumber = 2901234564;\n// \"2901234564\"\nconst deNumber = testNumber.toLocaleString(\"de\");\n// \"2.901.234.564\"\nconst frNumber = testNumber.toLocaleString(\"fr\");\n// \"2 901 234 564\"\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-object.prototype.tolocalestring |", "code_snippets": ["const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n\nconsole.log(date.toLocaleString(\"ar-EG\"));\n// Expected output: \"\u0662\u0660\u200f/\u0661\u0662\u200f/\u0662\u0660\u0661\u0662 \u0664:\u0660\u0660:\u0660\u0660 \u0635\"\n\nconst number = 123456.789;\n\nconsole.log(number.toLocaleString(\"de-DE\"));\n// Expected output: \"123.456,789\"\n", "toLocaleString()\n", "const obj = {\n toString() {\n return \"My Object\";\n },\n};\nconsole.log(obj.toLocaleString()); // \"My Object\"\n", "const testArray = [4, 7, 10];\n\nconst euroPrices = testArray.toLocaleString(\"fr\", {\n style: \"currency\",\n currency: \"EUR\",\n});\n// \"4,00 \u20ac,7,00 \u20ac,10,00 \u20ac\"\n", "const testDate = new Date();\n// \"Fri May 29 2020 18:04:24 GMT+0100 (British Summer Time)\"\n\nconst deDate = testDate.toLocaleString(\"de\");\n// \"29.5.2020, 18:04:24\"\n\nconst frDate = testDate.toLocaleString(\"fr\");\n// \"29/05/2020, 18:04:24\"\n", "const testNumber = 2901234564;\n// \"2901234564\"\n\nconst deNumber = testNumber.toLocaleString(\"de\");\n// \"2.901.234.564\"\n\nconst frNumber = testNumber.toLocaleString(\"fr\");\n// \"2 901 234 564\"\n"], "language": "JavaScript", "source": "mdn", "token_count": 955} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/toLocaleString", "title": "BigInt.prototype.toLocaleString()", "content": "BigInt.prototype.toLocaleString()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since September 2020.\nThe toLocaleString()\nmethod of BigInt\nvalues returns a string with a language-sensitive representation of this BigInt. In implementations with Intl.NumberFormat\nAPI support, this method delegates to Intl.NumberFormat\n.\nEvery time toLocaleString\nis called, it has to perform a search in a big database of localization strings, which is potentially inefficient. When the method is called many times with the same arguments, it is better to create an Intl.NumberFormat\nobject and use its format()\nmethod, because a NumberFormat\nobject remembers the arguments passed to it and may decide to cache a slice of the database, so future format\ncalls can search for localization strings within a more constrained context.\nTry it\nconst bigint = 123456789123456789n;\n// German uses period for thousands\nconsole.log(bigint.toLocaleString(\"de-DE\"));\n// Expected output: \"123.456.789.123.456.789\"\n// Request a currency format\nconsole.log(\nbigint.toLocaleString(\"de-DE\", { style: \"currency\", currency: \"EUR\" }),\n);\n// Expected output: \"123.456.789.123.456.789,00 \u20ac\"\nSyntax\ntoLocaleString()\ntoLocaleString(locales)\ntoLocaleString(locales, options)\nParameters\nThe locales\nand options\nparameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.\nIn implementations that support the Intl.NumberFormat\nAPI, these parameters correspond exactly to the Intl.NumberFormat()\nconstructor's parameters. Implementations without Intl.NumberFormat\nsupport are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.\nlocales\nOptional-\nA string with a BCP 47 language tag, or an array of such strings. Corresponds to the\nlocales\nparameter of theIntl.NumberFormat()\nconstructor.In implementations without\nIntl.NumberFormat\nsupport, this parameter is ignored and the host's locale is usually used. options\nOptional-\nAn object adjusting the output format. Corresponds to the\noptions\nparameter of theIntl.NumberFormat()\nconstructor.In implementations without\nIntl.NumberFormat\nsupport, this parameter is ignored.\nSee the Intl.NumberFormat()\nconstructor for details on these parameters and how to use them.\nReturn value\nA string representing the given BigInt according to language-specific conventions.\nIn implementations with Intl.NumberFormat\n, this is equivalent to new Intl.NumberFormat(locales, options).format(number)\n.\nNote:\nMost of the time, the formatting returned by toLocaleString()\nis consistent. However, the output may vary between implementations, even within the same locale \u2014 output variations are by design and allowed by the specification. It may also not be what you expect. For example, the string may use non-breaking spaces or be surrounded by bidirectional control characters. You should not compare the results of toLocaleString()\nto hardcoded constants.\nExamples\nUsing toLocaleString()\nBasic use of this method without specifying a locale\nreturns a formatted string in the default locale and with default options.\nconst bigint = 3500n;\nconsole.log(bigint.toLocaleString());\n// \"3,500\" if in U.S. English locale\nChecking for support for locales and options parameters\nThe locales\nand options\nparameters may not be supported in all implementations, because support for the internationalization API is optional, and some systems may not have the necessary data. For implementations without internationalization support, toLocaleString()\nalways uses the system's locale, which may not be what you want. Because any implementation that supports the locales\nand options\nparameters must support the Intl\nAPI, you can check the existence of the latter for support:\nfunction toLocaleStringSupportsLocales() {\nreturn (\ntypeof Intl === \"object\" &&\n!!Intl &&\ntypeof Intl.NumberFormat === \"function\"\n);\n}\nUsing locales\nThis example shows some of the variations in localized number formats. In order to get\nthe format of the language used in the user interface of your application, make sure to\nspecify that language (and possibly some fallback languages) using the\nlocales\nargument:\nconst bigint = 123456789123456789n;\n// German uses period for thousands\nconsole.log(bigint.toLocaleString(\"de-DE\"));\n// 123.456.789.123.456.789\n// Arabic in most Arabic speaking countries uses Eastern Arabic digits\nconsole.log(bigint.toLocaleString(\"ar-EG\"));\n// \u0661\u0662\u0663\u066c\u0664\u0665\u0666\u066c\u0667\u0668\u0669\u066c\u0661\u0662\u0663\u066c\u0664\u0665\u0666\u066c\u0667\u0668\u0669\n// India uses thousands/lakh/crore separators\nconsole.log(bigint.toLocaleString(\"en-IN\"));\n// 1,23,45,67,89,12,34,56,789\n// the nu extension key requests a numbering system, e.g. Chinese decimal\nconsole.log(bigint.toLocaleString(\"zh-Hans-CN-u-nu-hanidec\"));\n// \u4e00\u4e8c\u4e09,\u56db\u4e94\u516d,\u4e03\u516b\u4e5d,\u4e00\u4e8c\u4e09,\u56db\u4e94\u516d,\u4e03\u516b\u4e5d\n// when requesting a language that may not be supported, such as\n// Balinese, include a fallback language, in this case Indonesian\nconsole.log(bigint.toLocaleString([\"ban\", \"id\"]));\n// 123.456.789.123.456.789\nUsing options\nThe results provided by toLocaleString()\ncan be customized using the options\nparameter:\nconst bigint = 123456789123456789n;\n// request a currency format\nconsole.log(\nbigint.toLocaleString(\"de-DE\", { style: \"currency\", currency: \"EUR\" }),\n);\n// 123.456.789.123.456.789,00 \u20ac\n// the Japanese yen doesn't use a minor unit\nconsole.log(\nbigint.toLocaleString(\"ja-JP\", { style: \"currency\", currency: \"JPY\" }),\n);\n// \uffe5123,456,789,123,456,789\n// limit to three significant digits\nconsole.log(bigint.toLocaleString(\"en-IN\", { maximumSignificantDigits: 3 }));\n// 1,23,00,00,00,00,00,00,000\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # sup-bigint.prototype.tolocalestring |", "code_snippets": ["const bigint = 123456789123456789n;\n\n// German uses period for thousands\nconsole.log(bigint.toLocaleString(\"de-DE\"));\n// Expected output: \"123.456.789.123.456.789\"\n\n// Request a currency format\nconsole.log(\n bigint.toLocaleString(\"de-DE\", { style: \"currency\", currency: \"EUR\" }),\n);\n// Expected output: \"123.456.789.123.456.789,00 \u20ac\"\n", "toLocaleString()\ntoLocaleString(locales)\ntoLocaleString(locales, options)\n", "const bigint = 3500n;\n\nconsole.log(bigint.toLocaleString());\n// \"3,500\" if in U.S. English locale\n", "function toLocaleStringSupportsLocales() {\n return (\n typeof Intl === \"object\" &&\n !!Intl &&\n typeof Intl.NumberFormat === \"function\"\n );\n}\n", "const bigint = 123456789123456789n;\n\n// German uses period for thousands\nconsole.log(bigint.toLocaleString(\"de-DE\"));\n// 123.456.789.123.456.789\n\n// Arabic in most Arabic speaking countries uses Eastern Arabic digits\nconsole.log(bigint.toLocaleString(\"ar-EG\"));\n// \u0661\u0662\u0663\u066c\u0664\u0665\u0666\u066c\u0667\u0668\u0669\u066c\u0661\u0662\u0663\u066c\u0664\u0665\u0666\u066c\u0667\u0668\u0669\n\n// India uses thousands/lakh/crore separators\nconsole.log(bigint.toLocaleString(\"en-IN\"));\n// 1,23,45,67,89,12,34,56,789\n\n// the nu extension key requests a numbering system, e.g. Chinese decimal\nconsole.log(bigint.toLocaleString(\"zh-Hans-CN-u-nu-hanidec\"));\n// \u4e00\u4e8c\u4e09,\u56db\u4e94\u516d,\u4e03\u516b\u4e5d,\u4e00\u4e8c\u4e09,\u56db\u4e94\u516d,\u4e03\u516b\u4e5d\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(bigint.toLocaleString([\"ban\", \"id\"]));\n// 123.456.789.123.456.789\n", "const bigint = 123456789123456789n;\n\n// request a currency format\nconsole.log(\n bigint.toLocaleString(\"de-DE\", { style: \"currency\", currency: \"EUR\" }),\n);\n// 123.456.789.123.456.789,00 \u20ac\n\n// the Japanese yen doesn't use a minor unit\nconsole.log(\n bigint.toLocaleString(\"ja-JP\", { style: \"currency\", currency: \"JPY\" }),\n);\n// \uffe5123,456,789,123,456,789\n\n// limit to three significant digits\nconsole.log(bigint.toLocaleString(\"en-IN\", { maximumSignificantDigits: 3 }));\n// 1,23,00,00,00,00,00,00,000\n"], "language": "JavaScript", "source": "mdn", "token_count": 1940} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto", "title": "Object.prototype.__proto__", "content": "Object.prototype.__proto__\nDeprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.\nWarning:\nChanging the [[Prototype]]\nof an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the obj.__proto__ = ...\nstatement, but may extend to any code that has access to any object whose [[Prototype]]\nhas been altered. You can read more in JavaScript engine fundamentals: optimizing prototypes.\nNote:\nThe use of __proto__\nis controversial and discouraged. Its existence and exact behavior have only been standardized as a legacy feature to ensure web compatibility, while it presents several security issues and footguns. For better support, prefer Object.getPrototypeOf()\n/Reflect.getPrototypeOf()\nand Object.setPrototypeOf()\n/Reflect.setPrototypeOf()\ninstead.\nThe __proto__\naccessor property of Object\ninstances exposes the [[Prototype]]\n(either an object or null\n) of this object.\nThe __proto__\nproperty can also be used in an object literal definition to set the object [[Prototype]]\non creation, as an alternative to Object.create()\n. See: object initializer / literal syntax. That syntax is standard and optimized for in implementations, and quite different from Object.prototype.__proto__\n.\nSyntax\nobj.__proto__\nReturn value\nIf used as a getter, returns the object's [[Prototype]]\n.\nExceptions\nTypeError\n-\nThrown if attempting to set the prototype of a non-extensible object or an immutable prototype exotic object, such as\nObject.prototype\norwindow\n.\nDescription\nThe __proto__\ngetter function exposes the value of the internal [[Prototype]]\nof an object. For objects created using an object literal (unless you use the prototype setter syntax), this value is Object.prototype\n. For objects created using array literals, this value is Array.prototype\n. For functions, this value is Function.prototype\n. You can read more about the prototype chain in Inheritance and the prototype chain.\nThe __proto__\nsetter allows the [[Prototype]]\nof an object to be mutated. The value provided must be an object or null\n. Providing any other value will do nothing.\nUnlike Object.getPrototypeOf()\nand Object.setPrototypeOf()\n, which are always available on Object\nas static properties and always reflect the [[Prototype]]\ninternal property, the __proto__\nproperty doesn't always exist as a property on all objects, and as a result doesn't reflect [[Prototype]]\nreliably.\nThe __proto__\nproperty is just an accessor property on Object.prototype\nconsisting of a getter and setter function. A property access for __proto__\nthat eventually consults Object.prototype\nwill find this property, but an access that does not consult Object.prototype\nwill not. If some other __proto__\nproperty is found before Object.prototype\nis consulted, that property will hide the one found on Object.prototype\n.\nnull\n-prototype objects don't inherit any property from Object.prototype\n, including the __proto__\naccessor property, so if you try to read __proto__\non such an object, the value is always undefined\nregardless of the object's actual [[Prototype]]\n, and any assignment to __proto__\nwould create a new property called __proto__\ninstead of setting the object's prototype. Furthermore, __proto__\ncan be redefined as an own property on any object instance through Object.defineProperty()\nwithout triggering the setter. In this case, __proto__\nwill no longer be an accessor for [[Prototype]]\n. Therefore, always prefer Object.getPrototypeOf()\nand Object.setPrototypeOf()\nfor setting and getting the [[Prototype]]\nof an object.\nExamples\nUsing __proto__\nfunction Circle() {}\nconst shape = {};\nconst circle = new Circle();\n// Set the object prototype.\n// DEPRECATED. This is for example purposes only. DO NOT DO THIS in real code.\nshape.__proto__ = circle;\n// Get the object prototype\nconsole.log(shape.__proto__ === Circle); // false\nfunction ShapeA() {}\nconst ShapeB = {\na() {\nconsole.log(\"aaa\");\n},\n};\nShapeA.prototype.__proto__ = ShapeB;\nconsole.log(ShapeA.prototype.__proto__); // { a: [Function: a] }\nconst shapeA = new ShapeA();\nshapeA.a(); // aaa\nconsole.log(ShapeA.prototype === shapeA.__proto__); // true\nfunction ShapeC() {}\nconst ShapeD = {\na() {\nconsole.log(\"a\");\n},\n};\nconst shapeC = new ShapeC();\nshapeC.__proto__ = ShapeD;\nshapeC.a(); // a\nconsole.log(ShapeC.prototype === shapeC.__proto__); // false\nfunction Test() {}\nTest.prototype.myName = function () {\nconsole.log(\"myName\");\n};\nconst test = new Test();\nconsole.log(test.__proto__ === Test.prototype); // true\ntest.myName(); // myName\nconst obj = {};\nobj.__proto__ = Test.prototype;\nobj.myName(); // myName\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-object.prototype.__proto__ |", "code_snippets": ["obj.__proto__\n", "function Circle() {}\nconst shape = {};\nconst circle = new Circle();\n\n// Set the object prototype.\n// DEPRECATED. This is for example purposes only. DO NOT DO THIS in real code.\nshape.__proto__ = circle;\n\n// Get the object prototype\nconsole.log(shape.__proto__ === Circle); // false\n", "function ShapeA() {}\nconst ShapeB = {\n a() {\n console.log(\"aaa\");\n },\n};\n\nShapeA.prototype.__proto__ = ShapeB;\nconsole.log(ShapeA.prototype.__proto__); // { a: [Function: a] }\n\nconst shapeA = new ShapeA();\nshapeA.a(); // aaa\nconsole.log(ShapeA.prototype === shapeA.__proto__); // true\n", "function ShapeC() {}\nconst ShapeD = {\n a() {\n console.log(\"a\");\n },\n};\n\nconst shapeC = new ShapeC();\nshapeC.__proto__ = ShapeD;\nshapeC.a(); // a\nconsole.log(ShapeC.prototype === shapeC.__proto__); // false\n", "function Test() {}\nTest.prototype.myName = function () {\n console.log(\"myName\");\n};\n\nconst test = new Test();\nconsole.log(test.__proto__ === Test.prototype); // true\ntest.myName(); // myName\n\nconst obj = {};\nobj.__proto__ = Test.prototype;\nobj.myName(); // myName\n"], "language": "JavaScript", "source": "mdn", "token_count": 1580} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/getCanonicalLocales/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/getcanonicallocales/index.md\n\n# Original Wiki contributors\nlonglho\nfscholz\nwbamberg\narai\nnmve\nSebastianz\neduardoboucas\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 63} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Now/instant/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/temporal/now/instant/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 39} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Now/timeZoneId", "title": "Temporal.Now.timeZoneId()", "content": "Temporal.Now.timeZoneId()\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe Temporal.Now.timeZoneId()\nstatic method returns a time zone identifier representing the system's current time zone. Most systems will return a primary time zone identifier such as \"America/New_York\"\n, though offset time zone identifier such as \"-04:00\"\nis possible too. The time zone identifier returned is the default time zone used by the other Temporal.Now\nmethods.\nSyntax\nTemporal.Now.timeZoneId()\nParameters\nNone.\nReturn value\nA valid time zone identifier representing the system's current time zone. The returned time zone identifier is never a non-primary time zone identifier (alias). For example, it would always return \"Asia/Kolkata\"\n(new name) instead of \"Asia/Calcutta\"\n(old name). For more information, see time zones and offsets.\nIf the implementation does not support time zones, the method always returns \"UTC\"\n.\nExamples\nGetting the system's current time zone\nconsole.log(Temporal.Now.timeZoneId()); // e.g.: \"America/New_York\"\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-temporal.now.timezoneid |", "code_snippets": ["Temporal.Now.timeZoneId()\n", "console.log(Temporal.Now.timeZoneId()); // e.g.: \"America/New_York\"\n"], "language": "JavaScript", "source": "mdn", "token_count": 316} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/description", "title": "Symbol.prototype.description", "content": "Symbol.prototype.description\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since January 2020.\nThe description\naccessor property of Symbol\nvalues returns a string containing the description of this symbol, or undefined\nif the symbol has no description.\nTry it\nconsole.log(Symbol(\"desc\").description);\n// Expected output: \"desc\"\nconsole.log(Symbol.iterator.description);\n// Expected output: \"Symbol.iterator\"\nconsole.log(Symbol.for(\"foo\").description);\n// Expected output: \"foo\"\nconsole.log(`${Symbol(\"foo\").description}bar`);\n// Expected output: \"foobar\"\nDescription\nSymbol\nobjects can be created with an optional description which can be used for debugging but not to access the symbol itself. The Symbol.prototype.description\nproperty can be used to read that description. It is different to Symbol.prototype.toString()\nas it does not contain the enclosing \"Symbol()\"\nstring. See the examples.\nExamples\nUsing description\njs\nSymbol(\"desc\").toString(); // \"Symbol(desc)\"\nSymbol(\"desc\").description; // \"desc\"\nSymbol(\"\").description; // \"\"\nSymbol().description; // undefined\n// well-known symbols\nSymbol.iterator.toString(); // \"Symbol(Symbol.iterator)\"\nSymbol.iterator.description; // \"Symbol.iterator\"\n// global symbols\nSymbol.for(\"foo\").toString(); // \"Symbol(foo)\"\nSymbol.for(\"foo\").description; // \"foo\"\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-symbol.prototype.description |", "code_snippets": ["console.log(Symbol(\"desc\").description);\n// Expected output: \"desc\"\n\nconsole.log(Symbol.iterator.description);\n// Expected output: \"Symbol.iterator\"\n\nconsole.log(Symbol.for(\"foo\").description);\n// Expected output: \"foo\"\n\nconsole.log(`${Symbol(\"foo\").description}bar`);\n// Expected output: \"foobar\"\n", "Symbol(\"desc\").toString(); // \"Symbol(desc)\"\nSymbol(\"desc\").description; // \"desc\"\nSymbol(\"\").description; // \"\"\nSymbol().description; // undefined\n\n// well-known symbols\nSymbol.iterator.toString(); // \"Symbol(Symbol.iterator)\"\nSymbol.iterator.description; // \"Symbol.iterator\"\n\n// global symbols\nSymbol.for(\"foo\").toString(); // \"Symbol(foo)\"\nSymbol.for(\"foo\").description; // \"foo\"\n"], "language": "JavaScript", "source": "mdn", "token_count": 552} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Now/instant", "title": "Temporal.Now.instant()", "content": "Temporal.Now.instant()\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe Temporal.Now.instant()\nstatic method returns the current time as a Temporal.Instant\nobject.\nSyntax\njs\nTemporal.Now.instant()\nParameters\nNone.\nReturn value\nA Temporal.Instant\nobject representing the current time, with potentially reduced precision.\nExamples\nMeasuring time elapsed\nThe following example measures two instants in time and calculates the duration between them, and gets the total duration in milliseconds:\njs\nconst start = Temporal.Now.instant();\n// Do something that takes time\nconst end = Temporal.Now.instant();\nconst duration = end.since(start);\nconsole.log(duration.total(\"milliseconds\"));\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-temporal.now.instant |", "code_snippets": ["Temporal.Now.instant()\n", "const start = Temporal.Now.instant();\n// Do something that takes time\nconst end = Temporal.Now.instant();\nconst duration = end.since(start);\nconsole.log(duration.total(\"milliseconds\"));\n"], "language": "JavaScript", "source": "mdn", "token_count": 259} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Duration/weeks", "title": "Temporal.Duration.prototype.weeks", "content": "Temporal.Duration.prototype.weeks\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe weeks\naccessor property of Temporal.Duration\ninstances returns an integer representing the number of weeks in the duration.\nUnless the duration is balanced, you cannot assume the range of this value, but you can know its sign by checking the duration's sign\nproperty. If it is balanced to a unit above weeks, the weeks\nabsolute value's range depends on the calendar (how many weeks are in a month or year).\nThe set accessor of weeks\nis undefined\n. You cannot change this property directly. Use the with()\nmethod to create a new Temporal.Duration\nobject with the desired new value.\nExamples\nUsing weeks\njs\nconst d1 = Temporal.Duration.from({ weeks: 1, days: 1 });\nconst d2 = Temporal.Duration.from({ weeks: -1, days: -1 });\nconst d3 = Temporal.Duration.from({ weeks: 1 });\nconst d4 = Temporal.Duration.from({ days: 7 });\nconsole.log(d1.weeks); // 1\nconsole.log(d2.weeks); // -1\nconsole.log(d3.weeks); // 1\nconsole.log(d4.weeks); // 0\n// Balance d4\nconst d4Balanced = d4.round({\nlargestUnit: \"weeks\",\nrelativeTo: Temporal.PlainDate.from(\"2021-01-01\"), // ISO 8601 calendar\n});\nconsole.log(d4Balanced.weeks); // 1\nconsole.log(d4Balanced.days); // 0\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-get-temporal.duration.prototype.weeks |\nBrowser compatibility\nSee also\nTemporal.Duration\nTemporal.Duration.prototype.years\nTemporal.Duration.prototype.months\nTemporal.Duration.prototype.days\nTemporal.Duration.prototype.hours\nTemporal.Duration.prototype.minutes\nTemporal.Duration.prototype.seconds\nTemporal.Duration.prototype.milliseconds\nTemporal.Duration.prototype.microseconds\nTemporal.Duration.prototype.nanoseconds", "code_snippets": ["const d1 = Temporal.Duration.from({ weeks: 1, days: 1 });\nconst d2 = Temporal.Duration.from({ weeks: -1, days: -1 });\nconst d3 = Temporal.Duration.from({ weeks: 1 });\nconst d4 = Temporal.Duration.from({ days: 7 });\n\nconsole.log(d1.weeks); // 1\nconsole.log(d2.weeks); // -1\nconsole.log(d3.weeks); // 1\nconsole.log(d4.weeks); // 0\n\n// Balance d4\nconst d4Balanced = d4.round({\n largestUnit: \"weeks\",\n relativeTo: Temporal.PlainDate.from(\"2021-01-01\"), // ISO 8601 calendar\n});\nconsole.log(d4Balanced.weeks); // 1\nconsole.log(d4Balanced.days); // 0\n"], "language": "JavaScript", "source": "mdn", "token_count": 580} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive", "title": "Symbol.toPrimitive", "content": "Symbol.toPrimitive\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since April 2017.\nThe Symbol.toPrimitive\nstatic data property represents the well-known symbol Symbol.toPrimitive\n. All type coercion algorithms look up this symbol on objects for the method that accepts a preferred type and returns a primitive representation of the object, before falling back to using the object's valueOf()\nand toString()\nmethods.\nTry it\nconst object = {\n[Symbol.toPrimitive](hint) {\nif (hint === \"number\") {\nreturn 42;\n}\nreturn null;\n},\n};\nconsole.log(+object);\n// Expected output: 42\nValue\nThe well-known symbol Symbol.toPrimitive\n.\nProperty attributes of Symbol.toPrimitive | |\n|---|---|\n| Writable | no |\n| Enumerable | no |\n| Configurable | no |\nDescription\nWith the help of the Symbol.toPrimitive\nproperty (used as a function value), an object can be converted to a primitive value. The function is called with a string argument hint\n, which specifies the preferred type of the result primitive value. The hint\nargument can be one of \"number\"\n, \"string\"\n, and \"default\"\n.\nThe \"number\"\nhint is used by numeric coercion algorithms. The \"string\"\nhint is used by the string coercion algorithm. The \"default\"\nhint is used by the primitive coercion algorithm. The hint\nonly acts as a weak signal of preference, and the implementation is free to ignore it (as Symbol.prototype[Symbol.toPrimitive]()\ndoes). The language does not enforce alignment between the hint\nand the result type, although [Symbol.toPrimitive]()\nmust return a primitive, or a TypeError\nis thrown.\nObjects without the [Symbol.toPrimitive]\nproperty are converted to primitives by calling the valueOf()\nand toString()\nmethods in different orders, which is explained in more detail in the type coercion section. [Symbol.toPrimitive]()\nallows full control over the primitive conversion process. For example, Date.prototype[Symbol.toPrimitive]()\ntreats \"default\"\nas if it's \"string\"\nand calls toString()\ninstead of valueOf()\n. Symbol.prototype[Symbol.toPrimitive]()\nignores the hint and always returns a symbol, which means even in string contexts, Symbol.prototype.toString()\nwon't be called, and Symbol\nobjects must always be explicitly converted to strings through String()\n.\nExamples\nModifying primitive values converted from an object\nFollowing example describes how Symbol.toPrimitive\nproperty can modify the primitive value converted from an object.\n// An object without Symbol.toPrimitive property.\nconst obj1 = {};\nconsole.log(+obj1); // NaN\nconsole.log(`${obj1}`); // \"[object Object]\"\nconsole.log(obj1 + \"\"); // \"[object Object]\"\n// An object with Symbol.toPrimitive property.\nconst obj2 = {\n[Symbol.toPrimitive](hint) {\nif (hint === \"number\") {\nreturn 10;\n}\nif (hint === \"string\") {\nreturn \"hello\";\n}\nreturn true;\n},\n};\nconsole.log(+obj2); // 10 \u2014 hint is \"number\"\nconsole.log(`${obj2}`); // \"hello\" \u2014 hint is \"string\"\nconsole.log(obj2 + \"\"); // \"true\" \u2014 hint is \"default\"\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-symbol.toprimitive |", "code_snippets": ["const object = {\n [Symbol.toPrimitive](hint) {\n if (hint === \"number\") {\n return 42;\n }\n return null;\n },\n};\n\nconsole.log(+object);\n// Expected output: 42\n", "// An object without Symbol.toPrimitive property.\nconst obj1 = {};\nconsole.log(+obj1); // NaN\nconsole.log(`${obj1}`); // \"[object Object]\"\nconsole.log(obj1 + \"\"); // \"[object Object]\"\n\n// An object with Symbol.toPrimitive property.\nconst obj2 = {\n [Symbol.toPrimitive](hint) {\n if (hint === \"number\") {\n return 10;\n }\n if (hint === \"string\") {\n return \"hello\";\n }\n return true;\n },\n};\nconsole.log(+obj2); // 10 \u2014 hint is \"number\"\nconsole.log(`${obj2}`); // \"hello\" \u2014 hint is \"string\"\nconsole.log(obj2 + \"\"); // \"true\" \u2014 hint is \"default\"\n"], "language": "JavaScript", "source": "mdn", "token_count": 972} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatRange/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/numberformat/formatrange/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 42} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/number/negative_infinity/index.md\n\n# Original Wiki contributors\nmfuji09\nfscholz\nrwaldron\nalattalatta\nwbamberg\ndoubleOrt\nweblzf\njameshkramer\nimagineer-aman\nMingun\nAlexChao\nSheppy\nethertank\nevilpie\nSevenspade\nMgjbot\nPtak82\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 87} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/numberformat/formattoparts/index.md\n\n# Original Wiki contributors\nstockiNail\nnuragic\nmfuji09\nwwahammy\nfscholz\nwbamberg\nsideshowbarker\nalexrussell\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 70} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/segmenter/index.md\n\n# Original Wiki contributors\nmpcsh\nromulocintra\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 50} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/date/tolocaletimestring/index.md\n\n# Original Wiki contributors\nmfuji09\nchrisbruford\nwbamberg\nfscholz\nsideshowbarker\nmika76\nleothorp\nSphinxKnight\nRobg1\nschalkneethling\njameshkramer\nthetalecrafter\neduardoboucas\nMingun\nNorbert\nSheppy\nethertank\nevilpie\npwalton\nDikrib\nBold\nPtak82\nMaian\nDria\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 104} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString", "title": "Object.prototype.toString()", "content": "Object.prototype.toString()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe toString()\nmethod of Object\ninstances returns a string representing this object. This method is meant to be overridden by derived objects for custom type coercion logic.\nTry it\nconst map = new Map();\nconsole.log(map.toString());\n// Expected output: \"[object Map]\"\nSyntax\ntoString()\nParameters\nBy default toString()\ntakes no parameters. However, objects that inherit from Object\nmay override it with their own implementations that do take parameters. For example, the Number.prototype.toString()\nand BigInt.prototype.toString()\nmethods take an optional radix\nparameter.\nReturn value\nA string representing the object.\nDescription\nJavaScript calls the toString\nmethod to convert an object to a primitive value. You rarely need to invoke the toString\nmethod yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.\nThis method is called in priority by string conversion, but numeric conversion and primitive conversion call valueOf()\nin priority. However, because the base valueOf()\nmethod returns an object, the toString()\nmethod is usually called in the end, unless the object overrides valueOf()\n. For example, +[1]\nreturns 1\n, because its toString()\nmethod returns \"1\"\n, which is then converted to a number.\nAll objects that inherit from Object.prototype\n(that is, all except null\n-prototype objects) inherit the toString()\nmethod. When you create a custom object, you can override toString()\nto call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a [Symbol.toPrimitive]()\nmethod, which allows even more control over the conversion process, and will always be preferred over valueOf\nor toString\nfor any type conversion.\nTo use the base Object.prototype.toString()\nwith an object that has it overridden (or to invoke it on null\nor undefined\n), you need to call Function.prototype.call()\nor Function.prototype.apply()\non it, passing the object you want to inspect as the first parameter (called thisArg\n).\nconst arr = [1, 2, 3];\narr.toString(); // \"1,2,3\"\nObject.prototype.toString.call(arr); // \"[object Array]\"\nObject.prototype.toString()\nreturns \"[object Type]\"\n, where Type\nis the object type. If the object has a Symbol.toStringTag\nproperty whose value is a string, that value will be used as the Type\n. Many built-in objects, including Map\nand Symbol\n, have a Symbol.toStringTag\n. Some objects predating ES6 do not have Symbol.toStringTag\n, but have a special tag nonetheless. They include (the tag is the same as the type name given below):\nThe arguments\nobject returns \"[object Arguments]\"\n. Everything else, including user-defined classes, unless with a custom Symbol.toStringTag\n, will return \"[object Object]\"\n.\nObject.prototype.toString()\ninvoked on null\nand undefined\nreturns [object Null]\nand [object Undefined]\n, respectively.\nExamples\nOverriding toString for custom objects\nYou can create a function to be called in place of the default toString()\nmethod. The toString()\nfunction you create should return a string value. If it returns an object and the method is called implicitly during type conversion, then its result is ignored and the value of a related method, valueOf()\n, is used instead, or a TypeError\nis thrown if none of these methods return a primitive.\nThe following code defines a Dog\nclass.\nclass Dog {\nconstructor(name, breed, color, sex) {\nthis.name = name;\nthis.breed = breed;\nthis.color = color;\nthis.sex = sex;\n}\n}\nIf you call the toString()\nmethod, either explicitly or implicitly, on an instance of Dog\n, it returns the default value inherited from Object\n:\nconst theDog = new Dog(\"Gabby\", \"Lab\", \"chocolate\", \"female\");\ntheDog.toString(); // \"[object Object]\"\n`${theDog}`; // \"[object Object]\"\nThe following code overrides the default toString()\nmethod. This method generates a string containing the name\n, breed\n, color\n, and sex\nof the object.\nclass Dog {\nconstructor(name, breed, color, sex) {\nthis.name = name;\nthis.breed = breed;\nthis.color = color;\nthis.sex = sex;\n}\ntoString() {\nreturn `Dog ${this.name} is a ${this.sex} ${this.color} ${this.breed}`;\n}\n}\nWith the preceding code in place, any time an instance of Dog\nis used in a string context, JavaScript automatically calls the toString()\nmethod.\nconst theDog = new Dog(\"Gabby\", \"Lab\", \"chocolate\", \"female\");\n`${theDog}`; // \"Dog Gabby is a female chocolate Lab\"\nUsing toString() to detect object class\ntoString()\ncan be used with every object and (by default) allows you to get its class.\nconst toString = Object.prototype.toString;\ntoString.call(new Date()); // [object Date]\ntoString.call(new String()); // [object String]\n// Math has its Symbol.toStringTag\ntoString.call(Math); // [object Math]\ntoString.call(undefined); // [object Undefined]\ntoString.call(null); // [object Null]\nUsing toString()\nin this way is unreliable; objects can change the behavior of Object.prototype.toString()\nby defining a Symbol.toStringTag\nproperty, leading to unexpected results. For example:\nconst myDate = new Date();\nObject.prototype.toString.call(myDate); // [object Date]\nmyDate[Symbol.toStringTag] = \"myDate\";\nObject.prototype.toString.call(myDate); // [object myDate]\nDate.prototype[Symbol.toStringTag] = \"prototype polluted\";\nObject.prototype.toString.call(new Date()); // [object prototype polluted]\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-object.prototype.tostring |", "code_snippets": ["const map = new Map();\n\nconsole.log(map.toString());\n// Expected output: \"[object Map]\"\n", "toString()\n", "const arr = [1, 2, 3];\n\narr.toString(); // \"1,2,3\"\nObject.prototype.toString.call(arr); // \"[object Array]\"\n", "class Dog {\n constructor(name, breed, color, sex) {\n this.name = name;\n this.breed = breed;\n this.color = color;\n this.sex = sex;\n }\n}\n", "const theDog = new Dog(\"Gabby\", \"Lab\", \"chocolate\", \"female\");\n\ntheDog.toString(); // \"[object Object]\"\n`${theDog}`; // \"[object Object]\"\n", "class Dog {\n constructor(name, breed, color, sex) {\n this.name = name;\n this.breed = breed;\n this.color = color;\n this.sex = sex;\n }\n toString() {\n return `Dog ${this.name} is a ${this.sex} ${this.color} ${this.breed}`;\n }\n}\n", "const theDog = new Dog(\"Gabby\", \"Lab\", \"chocolate\", \"female\");\n\n`${theDog}`; // \"Dog Gabby is a female chocolate Lab\"\n", "const toString = Object.prototype.toString;\n\ntoString.call(new Date()); // [object Date]\ntoString.call(new String()); // [object String]\n// Math has its Symbol.toStringTag\ntoString.call(Math); // [object Math]\n\ntoString.call(undefined); // [object Undefined]\ntoString.call(null); // [object Null]\n", "const myDate = new Date();\nObject.prototype.toString.call(myDate); // [object Date]\n\nmyDate[Symbol.toStringTag] = \"myDate\";\nObject.prototype.toString.call(myDate); // [object myDate]\n\nDate.prototype[Symbol.toStringTag] = \"prototype polluted\";\nObject.prototype.toString.call(new Date()); // [object prototype polluted]\n"], "language": "JavaScript", "source": "mdn", "token_count": 1772} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/operators/object_initializer/index.md\n\n# Original Wiki contributors\nsharq\nMuhammad_Ali\nAnonymous\nfscholz\nwbamberg\njinbeomhong\nZearin_Galaurum\nmuhammadghazali\nsideshowbarker\nMadaraUchiha\nlmcarreiro\nJonathanPool\ntorazaburo\njameshkramer\nmartinczerwi\nbergus\nzbjornson\nnmve\nchrisjimallen\nkdex\nroryokane\nrwaldron\nstevemasta34\nkayellpeee\nbouzlibop\nhovosanoyan\nstevemao\nOlson.dev\nLlbe\njpmedley\nRobg1\nPhilip Chee\nWaldo\ntschneidereit\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 134} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat", "title": "Intl.ListFormat", "content": "Intl.ListFormat\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since April 2021.\nThe Intl.ListFormat\nobject enables language-sensitive list formatting.\nTry it\nconst vehicles = [\"Motorcycle\", \"Bus\", \"Car\"];\nconst formatter = new Intl.ListFormat(\"en\", {\nstyle: \"long\",\ntype: \"conjunction\",\n});\nconsole.log(formatter.format(vehicles));\n// Expected output: \"Motorcycle, Bus, and Car\"\nconst formatter2 = new Intl.ListFormat(\"de\", {\nstyle: \"short\",\ntype: \"disjunction\",\n});\nconsole.log(formatter2.format(vehicles));\n// Expected output: \"Motorcycle, Bus oder Car\"\nconst formatter3 = new Intl.ListFormat(\"en\", { style: \"narrow\", type: \"unit\" });\nconsole.log(formatter3.format(vehicles));\n// Expected output: \"Motorcycle Bus Car\"\nConstructor\nIntl.ListFormat()\n-\nCreates a new\nIntl.ListFormat\nobject.\nStatic methods\nIntl.ListFormat.supportedLocalesOf()\n-\nReturns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.\nInstance properties\nThese properties are defined on Intl.ListFormat.prototype\nand shared by all Intl.ListFormat\ninstances.\nIntl.ListFormat.prototype.constructor\n-\nThe constructor function that created the instance object. For\nIntl.ListFormat\ninstances, the initial value is theIntl.ListFormat\nconstructor. Intl.ListFormat.prototype[Symbol.toStringTag]\n-\nThe initial value of the\n[Symbol.toStringTag]\nproperty is the string\"Intl.ListFormat\"\n. This property is used inObject.prototype.toString()\n.\nInstance methods\nIntl.ListFormat.prototype.format()\n-\nReturns a language-specific formatted string representing the elements of the list.\nIntl.ListFormat.prototype.formatToParts()\n-\nReturns an array of objects representing the different components that can be used to format a list of values in a locale-aware fashion.\nIntl.ListFormat.prototype.resolvedOptions()\n-\nReturns a new object with properties reflecting the locale and style formatting options computed during the construction of the current\nIntl.ListFormat\nobject.\nExamples\nUsing format\nThe following example shows how to create a List formatter using the English language.\nconst list = [\"Motorcycle\", \"Bus\", \"Car\"];\nconsole.log(\nnew Intl.ListFormat(\"en-GB\", { style: \"long\", type: \"conjunction\" }).format(\nlist,\n),\n);\n// Motorcycle, Bus and Car\nconsole.log(\nnew Intl.ListFormat(\"en-GB\", { style: \"short\", type: \"disjunction\" }).format(\nlist,\n),\n);\n// Motorcycle, Bus or Car\nconsole.log(\nnew Intl.ListFormat(\"en-GB\", { style: \"narrow\", type: \"unit\" }).format(list),\n);\n// Motorcycle Bus Car\nUsing formatToParts\nThe following example shows how to create a List formatter returning formatted parts\nconst list = [\"Motorcycle\", \"Bus\", \"Car\"];\nconsole.log(\nnew Intl.ListFormat(\"en-GB\", {\nstyle: \"long\",\ntype: \"conjunction\",\n}).formatToParts(list),\n);\n// [ { \"type\": \"element\", \"value\": \"Motorcycle\" },\n// { \"type\": \"literal\", \"value\": \", \" },\n// { \"type\": \"element\", \"value\": \"Bus\" },\n// { \"type\": \"literal\", \"value\": \", and \" },\n// { \"type\": \"element\", \"value\": \"Car\" } ];\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Internationalization API Specification # listformat-objects |", "code_snippets": ["const vehicles = [\"Motorcycle\", \"Bus\", \"Car\"];\n\nconst formatter = new Intl.ListFormat(\"en\", {\n style: \"long\",\n type: \"conjunction\",\n});\nconsole.log(formatter.format(vehicles));\n// Expected output: \"Motorcycle, Bus, and Car\"\n\nconst formatter2 = new Intl.ListFormat(\"de\", {\n style: \"short\",\n type: \"disjunction\",\n});\nconsole.log(formatter2.format(vehicles));\n// Expected output: \"Motorcycle, Bus oder Car\"\n\nconst formatter3 = new Intl.ListFormat(\"en\", { style: \"narrow\", type: \"unit\" });\nconsole.log(formatter3.format(vehicles));\n// Expected output: \"Motorcycle Bus Car\"\n", "const list = [\"Motorcycle\", \"Bus\", \"Car\"];\n\nconsole.log(\n new Intl.ListFormat(\"en-GB\", { style: \"long\", type: \"conjunction\" }).format(\n list,\n ),\n);\n// Motorcycle, Bus and Car\n\nconsole.log(\n new Intl.ListFormat(\"en-GB\", { style: \"short\", type: \"disjunction\" }).format(\n list,\n ),\n);\n// Motorcycle, Bus or Car\n\nconsole.log(\n new Intl.ListFormat(\"en-GB\", { style: \"narrow\", type: \"unit\" }).format(list),\n);\n// Motorcycle Bus Car\n", "const list = [\"Motorcycle\", \"Bus\", \"Car\"];\nconsole.log(\n new Intl.ListFormat(\"en-GB\", {\n style: \"long\",\n type: \"conjunction\",\n }).formatToParts(list),\n);\n\n// [ { \"type\": \"element\", \"value\": \"Motorcycle\" },\n// { \"type\": \"literal\", \"value\": \", \" },\n// { \"type\": \"element\", \"value\": \"Bus\" },\n// { \"type\": \"literal\", \"value\": \", and \" },\n// { \"type\": \"element\", \"value\": \"Car\" } ];\n"], "language": "JavaScript", "source": "mdn", "token_count": 1158} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Duration/minutes", "title": "Temporal.Duration.prototype.minutes", "content": "Temporal.Duration.prototype.minutes\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe minutes\naccessor property of Temporal.Duration\ninstances returns an integer representing the number of minutes in the duration.\nUnless the duration is balanced, you cannot assume the range of this value, but you can know its sign by checking the duration's sign\nproperty. If it is balanced to a unit above minutes, the minutes\nabsolute value will be between 0 and 59, inclusive.\nThe set accessor of minutes\nis undefined\n. You cannot change this property directly. Use the with()\nmethod to create a new Temporal.Duration\nobject with the desired new value.\nExamples\nUsing minutes\njs\nconst d1 = Temporal.Duration.from({ hours: 1, minutes: 30 });\nconst d2 = Temporal.Duration.from({ hours: -1, minutes: -30 });\nconst d3 = Temporal.Duration.from({ hours: 1 });\nconst d4 = Temporal.Duration.from({ minutes: 60 });\nconsole.log(d1.minutes); // 1\nconsole.log(d2.minutes); // -1\nconsole.log(d3.minutes); // 0\nconsole.log(d4.minutes); // 60\n// Balance d4\nconst d4Balanced = d4.round({ largestUnit: \"hours\" });\nconsole.log(d4Balanced.minutes); // 0\nconsole.log(d4Balanced.hours); // 1\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-get-temporal.duration.prototype.minutes |\nBrowser compatibility\nSee also\nTemporal.Duration\nTemporal.Duration.prototype.years\nTemporal.Duration.prototype.months\nTemporal.Duration.prototype.weeks\nTemporal.Duration.prototype.days\nTemporal.Duration.prototype.hours\nTemporal.Duration.prototype.seconds\nTemporal.Duration.prototype.milliseconds\nTemporal.Duration.prototype.microseconds\nTemporal.Duration.prototype.nanoseconds", "code_snippets": ["const d1 = Temporal.Duration.from({ hours: 1, minutes: 30 });\nconst d2 = Temporal.Duration.from({ hours: -1, minutes: -30 });\nconst d3 = Temporal.Duration.from({ hours: 1 });\nconst d4 = Temporal.Duration.from({ minutes: 60 });\n\nconsole.log(d1.minutes); // 1\nconsole.log(d2.minutes); // -1\nconsole.log(d3.minutes); // 0\nconsole.log(d4.minutes); // 60\n\n// Balance d4\nconst d4Balanced = d4.round({ largestUnit: \"hours\" });\nconsole.log(d4Balanced.minutes); // 0\nconsole.log(d4Balanced.hours); // 1\n"], "language": "JavaScript", "source": "mdn", "token_count": 549} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality", "title": "Strict equality (===)", "content": "Strict equality (===)\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe strict equality (===\n) operator checks whether its two operands are\nequal, returning a Boolean result. Unlike the equality operator,\nthe strict equality operator always considers operands of different types to be\ndifferent.\nTry it\nconsole.log(1 === 1);\n// Expected output: true\nconsole.log(\"hello\" === \"hello\");\n// Expected output: true\nconsole.log(\"1\" === 1);\n// Expected output: false\nconsole.log(0 === false);\n// Expected output: false\nSyntax\njs\nx === y\nDescription\nThe strict equality operators (===\nand !==\n) provide the IsStrictlyEqual semantic.\n- If the operands are of different types, return\nfalse\n. - If both operands are objects, return\ntrue\nonly if they refer to the same object. - If both operands are\nnull\nor both operands areundefined\n, returntrue\n. - If either operand is\nNaN\n, returnfalse\n. - Otherwise, compare the two operand's values:\n- Numbers must have the same numeric values.\n+0\nand-0\nare considered to be the same value. - Strings must have the same characters in the same order.\n- Booleans must be both\ntrue\nor bothfalse\n.\n- Numbers must have the same numeric values.\nThe most notable difference between this operator and the equality\n(==\n) operator is that if the operands are of different types, the\n==\noperator attempts to convert them to the same type before comparing.\nExamples\nComparing operands of the same type\njs\n\"hello\" === \"hello\"; // true\n\"hello\" === \"hola\"; // false\n3 === 3; // true\n3 === 4; // false\ntrue === true; // true\ntrue === false; // false\nnull === null; // true\nComparing operands of different types\njs\n\"3\" === 3; // false\ntrue === 1; // false\nnull === undefined; // false\n3 === new Number(3); // false\nComparing objects\njs\nconst object1 = {\nkey: \"value\",\n};\nconst object2 = {\nkey: \"value\",\n};\nconsole.log(object1 === object2); // false\nconsole.log(object1 === object1); // true\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-equality-operators |", "code_snippets": ["console.log(1 === 1);\n// Expected output: true\n\nconsole.log(\"hello\" === \"hello\");\n// Expected output: true\n\nconsole.log(\"1\" === 1);\n// Expected output: false\n\nconsole.log(0 === false);\n// Expected output: false\n", "x === y\n", "\"hello\" === \"hello\"; // true\n\"hello\" === \"hola\"; // false\n\n3 === 3; // true\n3 === 4; // false\n\ntrue === true; // true\ntrue === false; // false\n\nnull === null; // true\n", "\"3\" === 3; // false\ntrue === 1; // false\nnull === undefined; // false\n3 === new Number(3); // false\n", "const object1 = {\n key: \"value\",\n};\n\nconst object2 = {\n key: \"value\",\n};\n\nconsole.log(object1 === object2); // false\nconsole.log(object1 === object1); // true\n"], "language": "JavaScript", "source": "mdn", "token_count": 693} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf", "title": "Object.prototype.valueOf()", "content": "Object.prototype.valueOf()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe valueOf()\nmethod of Object\ninstances converts the this\nvalue to an object. This method is meant to be overridden by derived objects for custom type conversion logic.\nTry it\nfunction MyNumberType(n) {\nthis.number = n;\n}\nMyNumberType.prototype.valueOf = function () {\nreturn this.number;\n};\nconst object = new MyNumberType(4);\nconsole.log(object + 3);\n// Expected output: 7\nSyntax\nvalueOf()\nParameters\nNone.\nReturn value\nThe this\nvalue, converted to an object.\nNote:\nIn order for valueOf\nto be useful during type conversion, it must return a primitive. Because all primitive types have their own valueOf()\nmethods, calling primitiveValue.valueOf()\ngenerally does not invoke Object.prototype.valueOf()\n.\nDescription\nJavaScript calls the valueOf\nmethod to convert an object to a primitive value. You rarely need to invoke the valueOf\nmethod yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.\nThis method is called in priority by numeric conversion and primitive conversion, but string conversion calls toString()\nin priority, and toString()\nis very likely to return a string value (even for the Object.prototype.toString()\nbase implementation), so valueOf()\nis usually not called in this case.\nAll objects that inherit from Object.prototype\n(that is, all except null\n-prototype objects) inherit the toString()\nmethod. The Object.prototype.valueOf()\nbase implementation is deliberately useless: by returning an object, its return value will never be used by any primitive conversion algorithm. Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override valueOf()\nto call a custom method, so that your custom object can be converted to a primitive value. Generally, valueOf()\nis used to return a value that is most meaningful for the object \u2014 unlike toString()\n, it does not need to be a string. Alternatively, you can add a [Symbol.toPrimitive]()\nmethod, which allows even more control over the conversion process, and will always be preferred over valueOf\nor toString\nfor any type conversion.\nExamples\nUsing valueOf()\nThe base valueOf()\nmethod returns the this\nvalue itself, converted to an object if it isn't already. Therefore its return value will never be used by any primitive conversion algorithm.\nconst obj = { foo: 1 };\nconsole.log(obj.valueOf() === obj); // true\nconsole.log(Object.prototype.valueOf.call(\"primitive\"));\n// [String: 'primitive'] (a wrapper object)\nOverriding valueOf for custom objects\nYou can create a function to be called in place of the default valueOf\nmethod. Your function should take no arguments, since it won't be passed any when called during type conversion.\nFor example, you can add a valueOf\nmethod to your custom class Box\n.\nclass Box {\n#value;\nconstructor(value) {\nthis.#value = value;\n}\nvalueOf() {\nreturn this.#value;\n}\n}\nWith the preceding code in place, any time an object of type Box\nis used in a context where it is to be represented as a primitive value (but not specifically a string), JavaScript automatically calls the function defined in the preceding code.\nconst box = new Box(123);\nconsole.log(box + 456); // 579\nconsole.log(box == 123); // true\nAn object's valueOf\nmethod is usually invoked by JavaScript, but you can invoke it yourself as follows:\nbox.valueOf();\nUsing unary plus on objects\nUnary plus performs number coercion on its operand, which, for most objects without [Symbol.toPrimitive]()\n, means calling its valueOf()\n. However, if the object doesn't have a custom valueOf()\nmethod, the base implementation will cause valueOf()\nto be ignored and the return value of toString()\nto be used instead.\n+new Date(); // the current timestamp; same as new Date().getTime()\n+{}; // NaN (toString() returns \"[object Object]\")\n+[]; // 0 (toString() returns an empty string list)\n+[1]; // 1 (toString() returns \"1\")\n+[1, 2]; // NaN (toString() returns \"1,2\")\n+new Set([1]); // NaN (toString() returns \"[object Set]\")\n+{ valueOf: () => 42 }; // 42\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-object.prototype.valueof |", "code_snippets": ["function MyNumberType(n) {\n this.number = n;\n}\n\nMyNumberType.prototype.valueOf = function () {\n return this.number;\n};\n\nconst object = new MyNumberType(4);\n\nconsole.log(object + 3);\n// Expected output: 7\n", "valueOf()\n", "const obj = { foo: 1 };\nconsole.log(obj.valueOf() === obj); // true\n\nconsole.log(Object.prototype.valueOf.call(\"primitive\"));\n// [String: 'primitive'] (a wrapper object)\n", "class Box {\n #value;\n constructor(value) {\n this.#value = value;\n }\n valueOf() {\n return this.#value;\n }\n}\n", "const box = new Box(123);\nconsole.log(box + 456); // 579\nconsole.log(box == 123); // true\n", "box.valueOf();\n", "+new Date(); // the current timestamp; same as new Date().getTime()\n+{}; // NaN (toString() returns \"[object Object]\")\n+[]; // 0 (toString() returns an empty string list)\n+[1]; // 1 (toString() returns \"1\")\n+[1, 2]; // NaN (toString() returns \"1,2\")\n+new Set([1]); // NaN (toString() returns \"[object Set]\")\n+{ valueOf: () => 42 }; // 42\n"], "language": "JavaScript", "source": "mdn", "token_count": 1321} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Duration/months", "title": "Temporal.Duration.prototype.months", "content": "Temporal.Duration.prototype.months\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe months\naccessor property of Temporal.Duration\ninstances returns an integer representing the number of months in the duration.\nUnless the duration is balanced, you cannot assume the range of this value, but you can know its sign by checking the duration's sign\nproperty. If it is balanced to a unit above months, the months\nabsolute value's range depends on the calendar (how many months are in a year).\nThe set accessor of months\nis undefined\n. You cannot change this property directly. Use the with()\nmethod to create a new Temporal.Duration\nobject with the desired new value.\nExamples\nUsing months\njs\nconst d1 = Temporal.Duration.from({ years: 1, months: 1 });\nconst d2 = Temporal.Duration.from({ years: -1, months: -1 });\nconst d3 = Temporal.Duration.from({ years: 1 });\nconst d4 = Temporal.Duration.from({ months: 12 });\nconsole.log(d1.months); // 1\nconsole.log(d2.months); // -1\nconsole.log(d3.months); // 0\nconsole.log(d4.months); // 12\n// Balance d4\nconst d4Balanced = d4.round({\nlargestUnit: \"years\",\nrelativeTo: Temporal.PlainDate.from(\"2021-01-01\"), // ISO 8601 calendar\n});\nconsole.log(d4Balanced.months); // 0\nconsole.log(d4Balanced.years); // 1\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-get-temporal.duration.prototype.months |\nBrowser compatibility\nSee also\nTemporal.Duration\nTemporal.Duration.prototype.years\nTemporal.Duration.prototype.weeks\nTemporal.Duration.prototype.days\nTemporal.Duration.prototype.hours\nTemporal.Duration.prototype.minutes\nTemporal.Duration.prototype.seconds\nTemporal.Duration.prototype.milliseconds\nTemporal.Duration.prototype.microseconds\nTemporal.Duration.prototype.nanoseconds", "code_snippets": ["const d1 = Temporal.Duration.from({ years: 1, months: 1 });\nconst d2 = Temporal.Duration.from({ years: -1, months: -1 });\nconst d3 = Temporal.Duration.from({ years: 1 });\nconst d4 = Temporal.Duration.from({ months: 12 });\n\nconsole.log(d1.months); // 1\nconsole.log(d2.months); // -1\nconsole.log(d3.months); // 0\nconsole.log(d4.months); // 12\n\n// Balance d4\nconst d4Balanced = d4.round({\n largestUnit: \"years\",\n relativeTo: Temporal.PlainDate.from(\"2021-01-01\"), // ISO 8601 calendar\n});\nconsole.log(d4Balanced.months); // 0\nconsole.log(d4Balanced.years); // 1\n"], "language": "JavaScript", "source": "mdn", "token_count": 587} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Malformed_URI/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/errors/malformed_uri/index.md\n\n# Original Wiki contributors\nfscholz\nPatrickKettner\nthornedlove\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 52} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Now", "title": "Temporal.Now", "content": "Temporal.Now\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe Temporal.Now\nnamespace object contains static methods for getting the current time in various formats.\nDescription\nUnlike most global objects, Temporal.Now\nis not a constructor. You cannot use it with the new\noperator or invoke the Temporal.Now\nobject as a function. All properties and methods of Temporal.Now\nare static (just like the Math\nobject).\nMost fundamentally, the system time is returned by the operating system as a time since the Unix epoch (usually millisecond-level precision, but might be nanosecond-level too). Temporal.Now.instant()\nreturns this time as a Temporal.Instant\nobject.\nAn instant can be interpreted in a time zone (which is the system time zone Temporal.Now.timeZoneId()\nby default) in the same fashion as Temporal.Instant.prototype.toZonedDateTimeISO()\n. To get a Temporal.ZonedDateTime\nobject, you can use Temporal.Now.zonedDateTimeISO()\n. You can also get different parts of the date and time, using Temporal.Now.plainDateISO()\n, Temporal.Now.plainTimeISO()\n, and Temporal.Now.plainDateTimeISO()\n.\nFor example, if the computer is set to the time zone \"America/New_York\", Temporal.Now.zonedDateTimeISO()\nreturns a zoned date-time like: 2021-08-01T10:40:12.345-04:00[America/New_York]\n. In this case, Temporal.Now.plainTimeISO()\nwould return the time part of this zoned date-time: 10:40:12.345\n. However, if you call Temporal.Now.plainTimeISO(\"UTC\")\n, it returns the time part of the zoned date-time in the UTC time zone: 14:40:12.345\n. This is especially useful for cross-system communication where the other end may be expecting the time in a different time zone.\nReduced time precision\nTo offer protection against timing attacks and fingerprinting, the precision of the Temporal.Now\nfunctions might get rounded depending on browser settings. In Firefox, the privacy.reduceTimerPrecision\npreference is enabled by default and defaults to 2ms. You can also enable privacy.resistFingerprinting\n, in which case the precision will be 100ms or the value of privacy.resistFingerprinting.reduceTimerPrecision.microseconds\n, whichever is larger.\nFor example, with reduced time precision, the result of Temporal.Now.instant().epochMilliseconds\nwill always be a multiple of 2, or a multiple of 100 (or privacy.resistFingerprinting.reduceTimerPrecision.microseconds\n) with privacy.resistFingerprinting\nenabled.\n// reduced time precision (2ms) in Firefox 60\nTemporal.Now.instant().epochMilliseconds;\n// Might be:\n// 1519211809934\n// 1519211810362\n// 1519211811670\n// \u2026\n// reduced time precision with `privacy.resistFingerprinting` enabled\nTemporal.Now.instant().epochMilliseconds;\n// Might be:\n// 1519129853500\n// 1519129858900\n// 1519129864400\n// \u2026\nStatic properties\nTemporal.Now[Symbol.toStringTag]\n-\nThe initial value of the\n[Symbol.toStringTag]\nproperty is the string\"Temporal.Now\"\n. This property is used inObject.prototype.toString()\n.\nStatic methods\nTemporal.Now.instant()\n-\nReturns the current time as a\nTemporal.Instant\nobject. Temporal.Now.plainDateISO()\n-\nReturns the current date as a\nTemporal.PlainDate\nobject, in the ISO 8601 calendar and the specified time zone. Temporal.Now.plainDateTimeISO()\n-\nReturns the current date and time as a\nTemporal.PlainDateTime\nobject, in the ISO 8601 calendar and the specified time zone. Temporal.Now.plainTimeISO()\n-\nReturns the current time as a\nTemporal.PlainTime\nobject, in the specified time zone. Temporal.Now.timeZoneId()\n-\nReturns a time zone identifier representing the system's current time zone.\nTemporal.Now.zonedDateTimeISO()\n-\nReturns the current date and time as a\nTemporal.ZonedDateTime\nobject, in the ISO 8601 calendar and the specified time zone.\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-temporal-now-object |", "code_snippets": ["// reduced time precision (2ms) in Firefox 60\nTemporal.Now.instant().epochMilliseconds;\n// Might be:\n// 1519211809934\n// 1519211810362\n// 1519211811670\n// \u2026\n\n// reduced time precision with `privacy.resistFingerprinting` enabled\nTemporal.Now.instant().epochMilliseconds;\n// Might be:\n// 1519129853500\n// 1519129858900\n// 1519129864400\n// \u2026\n"], "language": "JavaScript", "source": "mdn", "token_count": 1045} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify", "title": "JSON.stringify()", "content": "JSON.stringify()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe JSON.stringify()\nstatic method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.\nTry it\nconsole.log(JSON.stringify({ x: 5, y: 6 }));\n// Expected output: '{\"x\":5,\"y\":6}'\nconsole.log(\nJSON.stringify([new Number(3), new String(\"false\"), new Boolean(false)]),\n);\n// Expected output: '[3,\"false\",false]'\nconsole.log(JSON.stringify({ x: [10, undefined, function () {}, Symbol(\"\")] }));\n// Expected output: '{\"x\":[10,null,null,null]}'\nconsole.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)));\n// Expected output: '\"2006-01-02T15:04:05.000Z\"'\nSyntax\nJSON.stringify(value)\nJSON.stringify(value, replacer)\nJSON.stringify(value, replacer, space)\nParameters\nvalue\n-\nThe value to convert to a JSON string.\nreplacer\nOptional-\nA function that alters the behavior of the stringification process, or an array of strings and numbers that specifies properties of\nvalue\nto be included in the output. Ifreplacer\nis an array, all elements in this array that are not strings or numbers (either primitives or wrapper objects), includingSymbol\nvalues, are completely ignored. Ifreplacer\nis anything other than a function or an array (e.g.,null\nor not provided), all string-keyed properties of the object are included in the resulting JSON string. space\nOptional-\nA string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes.\nIf this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than\n10\nis treated as if it were10\n). Values less than 1 indicate that no space should be used.If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array.\nIf\nspace\nis anything other than a string or number (can be either a primitive or a wrapper object) \u2014 for example, isnull\nor not provided \u2014 no white space is used.\nReturn value\nA JSON string representing the given value, or undefined.\nExceptions\nDescription\nJSON.stringify()\nconverts a value to the JSON notation that the value represents. Values are stringified in the following manner:\nBoolean\n,Number\n,String\n, andBigInt\n(obtainable viaObject()\n) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics.Symbol\nobjects (obtainable viaObject()\n) are treated as plain objects.- Attempting to serialize\nBigInt\nvalues will throw. However, if the BigInt has atoJSON()\nmethod (through monkey patching:BigInt.prototype.toJSON = ...\n), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user. undefined\n,Function\n, andSymbol\nvalues are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed tonull\n(when found in an array).JSON.stringify()\ncan returnundefined\nwhen passing in \"pure\" values likeJSON.stringify(() => {})\norJSON.stringify(undefined)\n.- The numbers\nInfinity\nandNaN\n, as well as the valuenull\n, are all considerednull\n. (But unlike the values in the previous point, they would never be omitted.) - Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and\nlength - 1\n(inclusive) are serialized; other properties are ignored. - The special raw JSON object created with\nJSON.rawJSON()\nis serialized as the raw JSON text it contains (by accessing itsrawJSON\nproperty). - For other objects:\n-\nAll\nSymbol\n-keyed properties will be completely ignored, even when using thereplacer\nparameter. -\nIf the value has a\ntoJSON()\nmethod, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by thetoJSON()\nmethod when called will be serialized.JSON.stringify()\ncallstoJSON\nwith one parameter, thekey\n, which has the same semantic as thekey\nparameter of thereplacer\nfunction:- if this object is a property value, the property name\n- if it is in an array, the index in the array, as a string\n- if\nJSON.stringify()\nwas directly called on this object, an empty string\nAll\nTemporal\nobjects implement thetoJSON()\nmethod, which returns a string (the same as callingtoString()\n). Thus, they will be serialized as strings. Similarly,Date\nobjects implementtoJSON()\n, which returns the same astoISOString()\n. -\nOnly enumerable own properties are visited. This means\nMap\n,Set\n, etc. will become\"{}\"\n. You can use thereplacer\nparameter to serialize them to something more useful.Properties are visited using the same algorithm as\nObject.keys()\n, which has a well-defined order and is stable across implementations. For example,JSON.stringify\non the same object will always produce the same string, andJSON.parse(JSON.stringify(obj))\nwould produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable).\n-\nThe replacer parameter\nThe replacer\nparameter can be either a function or an array.\nAs an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored.\nAs a function, it takes two parameters: the key\nand the value\nbeing stringified. The object in which the key was found is provided as the replacer\n's this\ncontext.\nThe replacer\nfunction is called for the initial object being stringified as well, in which case the key\nis an empty string (\"\"\n). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as key\n. The current property value will be replaced with the replacer\n's return value for stringification. This means:\n- If you return a number, string, boolean, or\nnull\n, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) - If you return a\nFunction\n,Symbol\n, orundefined\n, the property is not included in the output. - If you return any other object, the object is recursively stringified, calling the\nreplacer\nfunction on each property.\nNote:\nWhen parsing JSON generated with replacer\nfunctions, you would likely want to use the reviver\nparameter to perform the reverse operation.\nTypically, array elements' index would never shift (even when the element is an invalid value like a function, it will become null\ninstead of omitted). Using the replacer\nfunction allows you to control the order of the array elements by returning a different array.\nThe space parameter\nThe space\nparameter may be used to control spacing in the final string.\n- If it is a number, successive levels in the stringification will each be indented by this many space characters.\n- If it is a string, successive levels will be indented by this string.\nEach level of indentation will never be longer than 10. Number values of space\nare clamped to 10, and string values are truncated to 10 characters.\nExamples\nUsing JSON.stringify\nJSON.stringify({}); // '{}'\nJSON.stringify(true); // 'true'\nJSON.stringify(\"foo\"); // '\"foo\"'\nJSON.stringify([1, \"false\", false]); // '[1,\"false\",false]'\nJSON.stringify([NaN, null, Infinity]); // '[null,null,null]'\nJSON.stringify({ x: 5 }); // '{\"x\":5}'\nJSON.stringify(new Date(1906, 0, 2, 15, 4, 5));\n// '\"1906-01-02T15:04:05.000Z\"'\nJSON.stringify({ x: 5, y: 6 });\n// '{\"x\":5,\"y\":6}'\nJSON.stringify([new Number(3), new String(\"false\"), new Boolean(false)]);\n// '[3,\"false\",false]'\n// String-keyed array elements are not enumerable and make no sense in JSON\nconst a = [\"foo\", \"bar\"];\na[\"baz\"] = \"quux\"; // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ]\nJSON.stringify(a);\n// '[\"foo\",\"bar\"]'\nJSON.stringify({ x: [10, undefined, function () {}, Symbol(\"\")] });\n// '{\"x\":[10,null,null,null]}'\n// Standard data structures\nJSON.stringify([\nnew Set([1]),\nnew Map([[1, 2]]),\nnew WeakSet([{ a: 1 }]),\nnew WeakMap([[{ a: 1 }, 2]]),\n]);\n// '[{},{},{},{}]'\n// TypedArray\nJSON.stringify([new Int8Array([1]), new Int16Array([1]), new Int32Array([1])]);\n// '[{\"0\":1},{\"0\":1},{\"0\":1}]'\nJSON.stringify([\nnew Uint8Array([1]),\nnew Uint8ClampedArray([1]),\nnew Uint16Array([1]),\nnew Uint32Array([1]),\n]);\n// '[{\"0\":1},{\"0\":1},{\"0\":1},{\"0\":1}]'\nJSON.stringify([new Float32Array([1]), new Float64Array([1])]);\n// '[{\"0\":1},{\"0\":1}]'\n// toJSON()\nJSON.stringify({\nx: 5,\ny: 6,\ntoJSON() {\nreturn this.x + this.y;\n},\n});\n// '11'\n// Symbols:\nJSON.stringify({ x: undefined, y: Object, z: Symbol(\"\") });\n// '{}'\nJSON.stringify({ [Symbol(\"foo\")]: \"foo\" });\n// '{}'\nJSON.stringify({ [Symbol.for(\"foo\")]: \"foo\" }, [Symbol.for(\"foo\")]);\n// '{}'\nJSON.stringify({ [Symbol.for(\"foo\")]: \"foo\" }, (k, v) => {\nif (typeof k === \"symbol\") {\nreturn \"a symbol\";\n}\n});\n// undefined\n// Non-enumerable properties:\nJSON.stringify(\nObject.create(null, {\nx: { value: \"x\", enumerable: false },\ny: { value: \"y\", enumerable: true },\n}),\n);\n// '{\"y\":\"y\"}'\n// BigInt values throw\nJSON.stringify({ x: 2n });\n// TypeError: BigInt value can't be serialized in JSON\nUsing a function as replacer\nfunction replacer(key, value) {\n// Filtering out properties\nif (typeof value === \"string\") {\nreturn undefined;\n}\nreturn value;\n}\nconst foo = {\nfoundation: \"Mozilla\",\nmodel: \"box\",\nweek: 45,\ntransport: \"car\",\nmonth: 7,\n};\nJSON.stringify(foo, replacer);\n// '{\"week\":45,\"month\":7}'\nIf you wish the replacer\nto distinguish an initial object from a key with an empty string property (since both would give the empty string as key and potentially an object as value), you will have to keep track of the iteration count (if it is beyond the first iteration, it is a genuine empty string key).\nfunction makeReplacer() {\nlet isInitial = true;\nreturn (key, value) => {\nif (isInitial) {\nisInitial = false;\nreturn value;\n}\nif (key === \"\") {\n// Omit all properties with name \"\" (except the initial object)\nreturn undefined;\n}\nreturn value;\n};\n}\nconst replacer = makeReplacer();\nconsole.log(JSON.stringify({ \"\": 1, b: 2 }, replacer)); // \"{\"b\":2}\"\nUsing an array as replacer\nconst foo = {\nfoundation: \"Mozilla\",\nmodel: \"box\",\nweek: 45,\ntransport: \"car\",\nmonth: 7,\n};\nJSON.stringify(foo, [\"week\", \"month\"]);\n// '{\"week\":45,\"month\":7}', only keep \"week\" and \"month\" properties\nUsing the space parameter\nIndent the output with one space:\nconsole.log(JSON.stringify({ a: 2 }, null, \" \"));\n/*\n{\n\"a\": 2\n}\n*/\nUsing a tab character mimics standard pretty-print appearance:\nconsole.log(JSON.stringify({ uno: 1, dos: 2 }, null, \"\\t\"));\n/*\n{\n\"uno\": 1,\n\"dos\": 2\n}\n*/\ntoJSON() behavior\nDefining toJSON()\nfor an object allows overriding its serialization behavior.\nconst obj = {\ndata: \"data\",\ntoJSON(key) {\nreturn key ? `Now I am a nested object under key '${key}'` : this;\n},\n};\nJSON.stringify(obj);\n// '{\"data\":\"data\"}'\nJSON.stringify({ obj });\n// '{\"obj\":\"Now I am a nested object under key 'obj'\"}'\nJSON.stringify([obj]);\n// '[\"Now I am a nested object under key '0'\"]'\nIssue with serializing circular references\nSince the JSON format doesn't support object references (although an IETF draft exists), a TypeError\nwill be thrown if one attempts to encode an object with circular references.\nconst circularReference = {};\ncircularReference.myself = circularReference;\n// Serializing circular references throws \"TypeError: cyclic object value\"\nJSON.stringify(circularReference);\nTo serialize circular references, you can use a library that supports them (e.g., cycle.js by Douglas Crockford) or implement a solution yourself, which will require finding and replacing (or removing) the cyclic references by serializable values.\nIf you are using JSON.stringify()\nto deep-copy an object, you may instead want to use structuredClone()\n, which supports circular references. JavaScript engine APIs for binary serialization, such as v8.serialize()\n, also support circular references.\nUsing JSON.stringify() with localStorage\nIn a case where you want to store an object created by your user and allow it to be restored even after the browser has been closed, the following example is a model for the applicability of JSON.stringify()\n:\n// Creating an example of JSON\nconst session = {\nscreens: [],\nstate: true,\n};\nsession.screens.push({ name: \"screenA\", width: 450, height: 250 });\nsession.screens.push({ name: \"screenB\", width: 650, height: 350 });\nsession.screens.push({ name: \"screenC\", width: 750, height: 120 });\nsession.screens.push({ name: \"screenD\", width: 250, height: 60 });\nsession.screens.push({ name: \"screenE\", width: 390, height: 120 });\nsession.screens.push({ name: \"screenF\", width: 1240, height: 650 });\n// Converting the JSON string with JSON.stringify()\n// then saving with localStorage in the name of session\nlocalStorage.setItem(\"session\", JSON.stringify(session));\n// Example of how to transform the String generated through\n// JSON.stringify() and saved in localStorage in JSON object again\nconst restoredSession = JSON.parse(localStorage.getItem(\"session\"));\n// Now restoredSession variable contains the object that was saved\n// in localStorage\nconsole.log(restoredSession);\nWell-formed JSON.stringify()\nEngines implementing the well-formed JSON.stringify specification will stringify lone surrogates (any code point from U+D800 to U+DFFF) using Unicode escape sequences rather than literally (outputting lone surrogates). Before this change, such strings could not be encoded in valid UTF-8 or UTF-16:\nJSON.stringify(\"\\uD800\"); // '\"\ufffd\"'\nBut with this change JSON.stringify()\nrepresents lone surrogates using JSON escape sequences that can be encoded in valid UTF-8 or UTF-16:\nJSON.stringify(\"\\uD800\"); // '\"\\\\ud800\"'\nThis change should be backwards-compatible as long as you pass the result of JSON.stringify()\nto APIs such as JSON.parse()\nthat will accept any valid JSON text, because they will treat Unicode escapes of lone surrogates as identical to the lone surrogates themselves. Only if you are directly interpreting the result of JSON.stringify()\ndo you need to carefully handle JSON.stringify()\n's two possible encodings of these code points.\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-json.stringify |", "code_snippets": ["console.log(JSON.stringify({ x: 5, y: 6 }));\n// Expected output: '{\"x\":5,\"y\":6}'\n\nconsole.log(\n JSON.stringify([new Number(3), new String(\"false\"), new Boolean(false)]),\n);\n// Expected output: '[3,\"false\",false]'\n\nconsole.log(JSON.stringify({ x: [10, undefined, function () {}, Symbol(\"\")] }));\n// Expected output: '{\"x\":[10,null,null,null]}'\n\nconsole.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)));\n// Expected output: '\"2006-01-02T15:04:05.000Z\"'\n", "JSON.stringify(value)\nJSON.stringify(value, replacer)\nJSON.stringify(value, replacer, space)\n", "JSON.stringify({}); // '{}'\nJSON.stringify(true); // 'true'\nJSON.stringify(\"foo\"); // '\"foo\"'\nJSON.stringify([1, \"false\", false]); // '[1,\"false\",false]'\nJSON.stringify([NaN, null, Infinity]); // '[null,null,null]'\nJSON.stringify({ x: 5 }); // '{\"x\":5}'\n\nJSON.stringify(new Date(1906, 0, 2, 15, 4, 5));\n// '\"1906-01-02T15:04:05.000Z\"'\n\nJSON.stringify({ x: 5, y: 6 });\n// '{\"x\":5,\"y\":6}'\nJSON.stringify([new Number(3), new String(\"false\"), new Boolean(false)]);\n// '[3,\"false\",false]'\n\n// String-keyed array elements are not enumerable and make no sense in JSON\nconst a = [\"foo\", \"bar\"];\na[\"baz\"] = \"quux\"; // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ]\nJSON.stringify(a);\n// '[\"foo\",\"bar\"]'\n\nJSON.stringify({ x: [10, undefined, function () {}, Symbol(\"\")] });\n// '{\"x\":[10,null,null,null]}'\n\n// Standard data structures\nJSON.stringify([\n new Set([1]),\n new Map([[1, 2]]),\n new WeakSet([{ a: 1 }]),\n new WeakMap([[{ a: 1 }, 2]]),\n]);\n// '[{},{},{},{}]'\n\n// TypedArray\nJSON.stringify([new Int8Array([1]), new Int16Array([1]), new Int32Array([1])]);\n// '[{\"0\":1},{\"0\":1},{\"0\":1}]'\nJSON.stringify([\n new Uint8Array([1]),\n new Uint8ClampedArray([1]),\n new Uint16Array([1]),\n new Uint32Array([1]),\n]);\n// '[{\"0\":1},{\"0\":1},{\"0\":1},{\"0\":1}]'\nJSON.stringify([new Float32Array([1]), new Float64Array([1])]);\n// '[{\"0\":1},{\"0\":1}]'\n\n// toJSON()\nJSON.stringify({\n x: 5,\n y: 6,\n toJSON() {\n return this.x + this.y;\n },\n});\n// '11'\n\n// Symbols:\nJSON.stringify({ x: undefined, y: Object, z: Symbol(\"\") });\n// '{}'\nJSON.stringify({ [Symbol(\"foo\")]: \"foo\" });\n// '{}'\nJSON.stringify({ [Symbol.for(\"foo\")]: \"foo\" }, [Symbol.for(\"foo\")]);\n// '{}'\nJSON.stringify({ [Symbol.for(\"foo\")]: \"foo\" }, (k, v) => {\n if (typeof k === \"symbol\") {\n return \"a symbol\";\n }\n});\n// undefined\n\n// Non-enumerable properties:\nJSON.stringify(\n Object.create(null, {\n x: { value: \"x\", enumerable: false },\n y: { value: \"y\", enumerable: true },\n }),\n);\n// '{\"y\":\"y\"}'\n\n// BigInt values throw\nJSON.stringify({ x: 2n });\n// TypeError: BigInt value can't be serialized in JSON\n", "function replacer(key, value) {\n // Filtering out properties\n if (typeof value === \"string\") {\n return undefined;\n }\n return value;\n}\n\nconst foo = {\n foundation: \"Mozilla\",\n model: \"box\",\n week: 45,\n transport: \"car\",\n month: 7,\n};\nJSON.stringify(foo, replacer);\n// '{\"week\":45,\"month\":7}'\n", "function makeReplacer() {\n let isInitial = true;\n\n return (key, value) => {\n if (isInitial) {\n isInitial = false;\n return value;\n }\n if (key === \"\") {\n // Omit all properties with name \"\" (except the initial object)\n return undefined;\n }\n return value;\n };\n}\n\nconst replacer = makeReplacer();\nconsole.log(JSON.stringify({ \"\": 1, b: 2 }, replacer)); // \"{\"b\":2}\"\n", "const foo = {\n foundation: \"Mozilla\",\n model: \"box\",\n week: 45,\n transport: \"car\",\n month: 7,\n};\n\nJSON.stringify(foo, [\"week\", \"month\"]);\n// '{\"week\":45,\"month\":7}', only keep \"week\" and \"month\" properties\n", "console.log(JSON.stringify({ a: 2 }, null, \" \"));\n/*\n{\n \"a\": 2\n}\n*/\n", "console.log(JSON.stringify({ uno: 1, dos: 2 }, null, \"\\t\"));\n/*\n{\n\t\"uno\": 1,\n\t\"dos\": 2\n}\n*/\n", "const obj = {\n data: \"data\",\n\n toJSON(key) {\n return key ? `Now I am a nested object under key '${key}'` : this;\n },\n};\n\nJSON.stringify(obj);\n// '{\"data\":\"data\"}'\n\nJSON.stringify({ obj });\n// '{\"obj\":\"Now I am a nested object under key 'obj'\"}'\n\nJSON.stringify([obj]);\n// '[\"Now I am a nested object under key '0'\"]'\n", "const circularReference = {};\ncircularReference.myself = circularReference;\n\n// Serializing circular references throws \"TypeError: cyclic object value\"\nJSON.stringify(circularReference);\n", "// Creating an example of JSON\nconst session = {\n screens: [],\n state: true,\n};\nsession.screens.push({ name: \"screenA\", width: 450, height: 250 });\nsession.screens.push({ name: \"screenB\", width: 650, height: 350 });\nsession.screens.push({ name: \"screenC\", width: 750, height: 120 });\nsession.screens.push({ name: \"screenD\", width: 250, height: 60 });\nsession.screens.push({ name: \"screenE\", width: 390, height: 120 });\nsession.screens.push({ name: \"screenF\", width: 1240, height: 650 });\n\n// Converting the JSON string with JSON.stringify()\n// then saving with localStorage in the name of session\nlocalStorage.setItem(\"session\", JSON.stringify(session));\n\n// Example of how to transform the String generated through\n// JSON.stringify() and saved in localStorage in JSON object again\nconst restoredSession = JSON.parse(localStorage.getItem(\"session\"));\n\n// Now restoredSession variable contains the object that was saved\n// in localStorage\nconsole.log(restoredSession);\n", "JSON.stringify(\"\\uD800\"); // '\"\ufffd\"'\n", "JSON.stringify(\"\\uD800\"); // '\"\\\\ud800\"'\n"], "language": "JavaScript", "source": "mdn", "token_count": 4939} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable", "title": "Object.prototype.propertyIsEnumerable()", "content": "Object.prototype.propertyIsEnumerable()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe propertyIsEnumerable()\nmethod of Object\ninstances returns a boolean indicating whether the specified property is this object's enumerable own property.\nTry it\nconst object = {};\nconst array = [];\nobject.foo = 42;\narray[0] = 42;\nconsole.log(object.propertyIsEnumerable(\"foo\"));\n// Expected output: true\nconsole.log(array.propertyIsEnumerable(0));\n// Expected output: true\nconsole.log(array.propertyIsEnumerable(\"length\"));\n// Expected output: false\nSyntax\npropertyIsEnumerable(prop)\nParameters\nReturn value\nA boolean value indicating whether the specified property is enumerable and is the object's own property.\nDescription\nAll objects that inherit from Object.prototype\n(that is, all except null\n-prototype objects) inherit the propertyIsEnumerable()\nmethod. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns false\n.\nThis method is equivalent to Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false\n.\nExamples\nUsing propertyIsEnumerable()\nThe following example shows the use of propertyIsEnumerable()\non objects and arrays.\nconst o = {};\nconst a = [];\no.prop = \"is enumerable\";\na[0] = \"is enumerable\";\no.propertyIsEnumerable(\"prop\"); // true\na.propertyIsEnumerable(0); // true\nUser-defined vs. built-in objects\nMost built-in properties are non-enumerable by default, while user-created object properties are often enumerable, unless explicitly designated otherwise.\nconst a = [\"is enumerable\"];\na.propertyIsEnumerable(0); // true\na.propertyIsEnumerable(\"length\"); // false\nMath.propertyIsEnumerable(\"random\"); // false\nglobalThis.propertyIsEnumerable(\"Math\"); // false\nDirect vs. inherited properties\nOnly enumerable own properties cause propertyIsEnumerable()\nto return true\n, although all enumerable properties, including inherited ones, are visited by the for...in\nloop.\nconst o1 = {\nenumerableInherited: \"is enumerable\",\n};\nObject.defineProperty(o1, \"nonEnumerableInherited\", {\nvalue: \"is non-enumerable\",\nenumerable: false,\n});\nconst o2 = {\n// o1 is the prototype of o2\n__proto__: o1,\nenumerableOwn: \"is enumerable\",\n};\nObject.defineProperty(o2, \"nonEnumerableOwn\", {\nvalue: \"is non-enumerable\",\nenumerable: false,\n});\no2.propertyIsEnumerable(\"enumerableInherited\"); // false\no2.propertyIsEnumerable(\"nonEnumerableInherited\"); // false\no2.propertyIsEnumerable(\"enumerableOwn\"); // true\no2.propertyIsEnumerable(\"nonEnumerableOwn\"); // false\nTesting symbol properties\nSymbol\nproperties are also supported by propertyIsEnumerable()\n. Note that most enumeration methods only visit string properties; enumerability of symbol properties is only useful when using Object.assign()\nor spread syntax. For more information, see Enumerability and ownership of properties.\nconst sym = Symbol(\"enumerable\");\nconst sym2 = Symbol(\"non-enumerable\");\nconst o = {\n[sym]: \"is enumerable\",\n};\nObject.defineProperty(o, sym2, {\nvalue: \"is non-enumerable\",\nenumerable: false,\n});\no.propertyIsEnumerable(sym); // true\no.propertyIsEnumerable(sym2); // false\nUsage with null-prototype objects\nBecause null\n-prototype objects do not inherit from Object.prototype\n, they do not inherit the propertyIsEnumerable()\nmethod. You must call Object.prototype.propertyIsEnumerable\nwith the object as this\ninstead.\nconst o = {\n__proto__: null,\nenumerableOwn: \"is enumerable\",\n};\no.propertyIsEnumerable(\"enumerableOwn\"); // TypeError: o.propertyIsEnumerable is not a function\nObject.prototype.propertyIsEnumerable.call(o, \"enumerableOwn\"); // true\nAlternatively, you may use Object.getOwnPropertyDescriptor()\ninstead, which also helps to distinguish between non-existent properties and actually non-enumerable properties.\nconst o = {\n__proto__: null,\nenumerableOwn: \"is enumerable\",\n};\nObject.getOwnPropertyDescriptor(o, \"enumerableOwn\")?.enumerable; // true\nObject.getOwnPropertyDescriptor(o, \"nonExistent\")?.enumerable; // undefined\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-object.prototype.propertyisenumerable |", "code_snippets": ["const object = {};\nconst array = [];\nobject.foo = 42;\narray[0] = 42;\n\nconsole.log(object.propertyIsEnumerable(\"foo\"));\n// Expected output: true\n\nconsole.log(array.propertyIsEnumerable(0));\n// Expected output: true\n\nconsole.log(array.propertyIsEnumerable(\"length\"));\n// Expected output: false\n", "propertyIsEnumerable(prop)\n", "const o = {};\nconst a = [];\no.prop = \"is enumerable\";\na[0] = \"is enumerable\";\n\no.propertyIsEnumerable(\"prop\"); // true\na.propertyIsEnumerable(0); // true\n", "const a = [\"is enumerable\"];\n\na.propertyIsEnumerable(0); // true\na.propertyIsEnumerable(\"length\"); // false\n\nMath.propertyIsEnumerable(\"random\"); // false\nglobalThis.propertyIsEnumerable(\"Math\"); // false\n", "const o1 = {\n enumerableInherited: \"is enumerable\",\n};\nObject.defineProperty(o1, \"nonEnumerableInherited\", {\n value: \"is non-enumerable\",\n enumerable: false,\n});\nconst o2 = {\n // o1 is the prototype of o2\n __proto__: o1,\n enumerableOwn: \"is enumerable\",\n};\nObject.defineProperty(o2, \"nonEnumerableOwn\", {\n value: \"is non-enumerable\",\n enumerable: false,\n});\n\no2.propertyIsEnumerable(\"enumerableInherited\"); // false\no2.propertyIsEnumerable(\"nonEnumerableInherited\"); // false\no2.propertyIsEnumerable(\"enumerableOwn\"); // true\no2.propertyIsEnumerable(\"nonEnumerableOwn\"); // false\n", "const sym = Symbol(\"enumerable\");\nconst sym2 = Symbol(\"non-enumerable\");\nconst o = {\n [sym]: \"is enumerable\",\n};\nObject.defineProperty(o, sym2, {\n value: \"is non-enumerable\",\n enumerable: false,\n});\n\no.propertyIsEnumerable(sym); // true\no.propertyIsEnumerable(sym2); // false\n", "const o = {\n __proto__: null,\n enumerableOwn: \"is enumerable\",\n};\n\no.propertyIsEnumerable(\"enumerableOwn\"); // TypeError: o.propertyIsEnumerable is not a function\nObject.prototype.propertyIsEnumerable.call(o, \"enumerableOwn\"); // true\n", "const o = {\n __proto__: null,\n enumerableOwn: \"is enumerable\",\n};\n\nObject.getOwnPropertyDescriptor(o, \"enumerableOwn\")?.enumerable; // true\nObject.getOwnPropertyDescriptor(o, \"nonExistent\")?.enumerable; // undefined\n"], "language": "JavaScript", "source": "mdn", "token_count": 1570} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Constructor_cant_be_used_directly", "title": "TypeError: Iterator/AsyncIterator constructor can't be used directly", "content": "TypeError: Iterator/AsyncIterator constructor can't be used directly\nThe JavaScript exception \"Iterator constructor can't be used directly\" or \"AsyncIterator constructor can't be used directly\" occurs when you try to use the Iterator()\nor AsyncIterator()\nconstructors directly to create instances. These constructors are abstract classes and should only be inherited from.\nMessage\nTypeError: Abstract class Iterator not directly constructable (V8-based) TypeError: Iterator constructor can't be used directly (Firefox) TypeError: Iterator cannot be constructed directly (Safari) TypeError: Abstract class AsyncIterator not directly constructable (V8-based) TypeError: AsyncIterator constructor can't be used directly (Firefox) TypeError: AsyncIterator cannot be constructed directly (Safari)\nError type\nTypeError\nWhat went wrong?\nThe Iterator\nand AsyncIterator\nconstructors are abstract classes and should not be used directly. They check the value of new.target\nand throw if it is the same as the constructor itself. The only way to use these constructors is to inherit from them in a subclass and call super()\nin the subclass constructor. The subclass must also define a next()\nmethod to be useful.\nExamples\nInvalid cases\njs\nnew Iterator();\nValid cases\njs\nclass MyIterator extends Iterator {\n#step;\n#end;\nconstructor(start, end) {\n// Implicitly calls new Iterator(), but with a different `new.target`\nsuper();\nthis.#step = start;\nthis.#end = end;\n}\nnext() {\nif (this.#step >= this.#end) {\nreturn { done: true };\n}\nreturn { value: this.#step++, done: false };\n}\n}\nnew MyIterator();", "code_snippets": ["new Iterator();\n", "class MyIterator extends Iterator {\n #step;\n #end;\n constructor(start, end) {\n // Implicitly calls new Iterator(), but with a different `new.target`\n super();\n this.#step = start;\n this.#end = end;\n }\n next() {\n if (this.#step >= this.#end) {\n return { done: true };\n }\n return { value: this.#step++, done: false };\n }\n}\n\nnew MyIterator();\n"], "language": "JavaScript", "source": "mdn", "token_count": 492} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/valueOf", "title": "String.prototype.valueOf()", "content": "String.prototype.valueOf()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe valueOf()\nmethod of String\nvalues returns this string value.\nTry it\nconst stringObj = new String(\"foo\");\nconsole.log(stringObj);\n// Expected output: String { \"foo\" }\nconsole.log(stringObj.valueOf());\n// Expected output: \"foo\"\nSyntax\njs\nvalueOf()\nParameters\nNone.\nReturn value\nA string representing the primitive value of a given String\nobject.\nDescription\nThe valueOf()\nmethod of String\nreturns the primitive value\nof a String\nobject as a string data type. This value is equivalent to\nString.prototype.toString()\n.\nThis method is usually called internally by JavaScript and not explicitly in code.\nExamples\nUsing valueOf()\njs\nconst x = new String(\"Hello world\");\nconsole.log(x.valueOf()); // 'Hello world'\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-string.prototype.valueof |", "code_snippets": ["const stringObj = new String(\"foo\");\n\nconsole.log(stringObj);\n// Expected output: String { \"foo\" }\n\nconsole.log(stringObj.valueOf());\n// Expected output: \"foo\"\n", "valueOf()\n", "const x = new String(\"Hello world\");\nconsole.log(x.valueOf()); // 'Hello world'\n"], "language": "JavaScript", "source": "mdn", "token_count": 316} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/resolvedOptions/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/durationformat/resolvedoptions/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 43} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/listformat/index.md\n\n# Original Wiki contributors\nlonglho\nmfuji09\nChris Chittleborough\nwbamberg\nfscholz\nnakhodkiin\nsideshowbarker\ncbejensen\nsenna\nSphinxKnight\nfacm0b\nspectranaut\nstof\nAutapomorph\nromulocintra\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 85} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax", "title": "Spread syntax (...)", "content": "Spread syntax (...)\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since October 2015.\nThe spread (...\n) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created.\nSpread syntax looks exactly like rest syntax. In a way, spread syntax is the opposite of rest syntax. Spread syntax \"expands\" an array into its elements, while rest syntax collects multiple elements and \"condenses\" them into a single element. See rest parameters and rest property.\nTry it\nfunction sum(x, y, z) {\nreturn x + y + z;\n}\nconst numbers = [1, 2, 3];\nconsole.log(sum(...numbers));\n// Expected output: 6\nconsole.log(sum.apply(null, numbers));\n// Expected output: 6\nSyntax\nmyFunction(a, ...iterableObj, b)\n[1, ...iterableObj, '4', 'five', 6]\n{ ...obj, key: 'value' }\nDescription\nSpread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list. There are three distinct places that accept the spread syntax:\n- Function arguments list (\nmyFunction(a, ...iterableObj, b)\n) - Array literals (\n[1, ...iterableObj, '4', 'five', 6]\n) - Object literals (\n{ ...obj, key: 'value' }\n)\nAlthough the syntax looks the same, they come with slightly different semantics.\nOnly iterable values, like Array\nand String\n, can be spread in array literals and argument lists. Many objects are not iterable, including all plain objects that lack a Symbol.iterator\nmethod:\nconst obj = { key1: \"value1\" };\nconst array = [...obj]; // TypeError: obj is not iterable\nOn the other hand, spreading in object literals enumerates the own properties of the value. For typical arrays, all indices are enumerable own properties, so arrays can be spread into objects.\nconst array = [1, 2, 3];\nconst obj = { ...array }; // { 0: 1, 1: 2, 2: 3 }\nAll primitives can be spread in objects. Only strings have enumerable own properties, and spreading anything else doesn't create properties on the new object.\nconst obj = { ...true, ...\"test\", ...10 };\n// { '0': 't', '1': 'e', '2': 's', '3': 't' }\nWhen using spread syntax for function calls, be aware of the possibility of exceeding the JavaScript engine's argument length limit. See Function.prototype.apply()\nfor more details.\nExamples\nSpread in function calls\nReplace apply()\nIt is common to use Function.prototype.apply()\nin cases where you want to\nuse the elements of an array as arguments to a function.\nfunction myFunction(x, y, z) {}\nconst args = [0, 1, 2];\nmyFunction.apply(null, args);\nWith spread syntax the above can be written as:\nfunction myFunction(x, y, z) {}\nconst args = [0, 1, 2];\nmyFunction(...args);\nAny argument in the argument list can use spread syntax, and the spread syntax can be used multiple times.\nfunction myFunction(v, w, x, y, z) {}\nconst args = [0, 1];\nmyFunction(-1, ...args, 2, ...[3]);\nApply for new operator\nWhen calling a constructor with new\n, it's not possible to directly use an array and apply()\n, because apply()\ncalls the target function instead of constructing it, which means, among other things, that new.target\nwill be undefined\n. However, an array can be easily used with new\nthanks to spread syntax:\nconst dateFields = [1970, 0, 1]; // 1 Jan 1970\nconst d = new Date(...dateFields);\nSpread in array literals\nA more powerful array literal\nWithout spread syntax, the array literal syntax is no longer sufficient to create a new array using an existing array as one part of it. Instead, imperative code must be used using a combination of methods, including push()\n, splice()\n, concat()\n, etc. With spread syntax, this becomes much more succinct:\nconst parts = [\"shoulders\", \"knees\"];\nconst lyrics = [\"head\", ...parts, \"and\", \"toes\"];\n// [\"head\", \"shoulders\", \"knees\", \"and\", \"toes\"]\nJust like spread for argument lists, ...\ncan be used anywhere in the array literal, and may be used more than once.\nCopying an array\nYou can use spread syntax to make a shallow copy of an array. Each array element retains its identity without getting copied.\nconst arr = [1, 2, 3];\nconst arr2 = [...arr]; // like arr.slice()\narr2.push(4);\n// arr2 becomes [1, 2, 3, 4]\n// arr remains unaffected\nSpread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays. The same is true with Object.assign()\n\u2014 no native operation in JavaScript does a deep clone. The web API method structuredClone()\nallows deep copying values of certain supported types. See shallow copy for more details.\nconst a = [[1], [2], [3]];\nconst b = [...a];\nb.shift().shift();\n// 1\n// Oh no! Now array 'a' is affected as well:\nconsole.log(a);\n// [[], [2], [3]]\nA better way to concatenate arrays\nArray.prototype.concat()\nis often used to concatenate an array to the end of an existing array. Without spread syntax, this is done as:\nlet arr1 = [0, 1, 2];\nconst arr2 = [3, 4, 5];\n// Append all items from arr2 onto arr1\narr1 = arr1.concat(arr2);\nWith spread syntax this becomes:\nlet arr1 = [0, 1, 2];\nconst arr2 = [3, 4, 5];\narr1 = [...arr1, ...arr2];\n// arr1 is now [0, 1, 2, 3, 4, 5]\nArray.prototype.unshift()\nis often used to insert an array of values at the start of an existing array. Without spread syntax, this is done as:\nconst arr1 = [0, 1, 2];\nconst arr2 = [3, 4, 5];\n// Prepend all items from arr2 onto arr1\nArray.prototype.unshift.apply(arr1, arr2);\nconsole.log(arr1); // [3, 4, 5, 0, 1, 2]\nWith spread syntax, this becomes:\nlet arr1 = [0, 1, 2];\nconst arr2 = [3, 4, 5];\narr1 = [...arr2, ...arr1];\nconsole.log(arr1); // [3, 4, 5, 0, 1, 2]\nNote:\nUnlike unshift()\n, this creates a new arr1\n, instead of modifying the original arr1\narray in-place.\nConditionally adding values to an array\nYou can make an element present or absent in an array literal, depending on a condition, using a conditional operator.\nconst isSummer = false;\nconst fruits = [\"apple\", \"banana\", ...(isSummer ? [\"watermelon\"] : [])];\n// ['apple', 'banana']\nWhen the condition is false\n, we spread an empty array, so that nothing gets added to the final array. Note that this is different from the following:\nconst fruits = [\"apple\", \"banana\", isSummer ? \"watermelon\" : undefined];\n// ['apple', 'banana', undefined]\nIn this case, an extra undefined\nelement is added when isSummer\nis false\n, and this element will be visited by methods such as Array.prototype.map()\n.\nSpread in object literals\nCopying and merging objects\nYou can use spread syntax to merge multiple objects into one new object.\nconst obj1 = { foo: \"bar\", x: 42 };\nconst obj2 = { bar: \"baz\", y: 13 };\nconst mergedObj = { ...obj1, ...obj2 };\n// { foo: \"bar\", x: 42, bar: \"baz\", y: 13 }\nA single spread creates a shallow copy of the original object (but without non-enumerable properties and without copying the prototype), similar to copying an array.\nconst clonedObj = { ...obj1 };\n// { foo: \"bar\", x: 42 }\nOverriding properties\nWhen one object is spread into another object, or when multiple objects are spread into one object, and properties with identical names are encountered, the property takes the last value assigned while remaining in the position it was originally set.\nconst obj1 = { foo: \"bar\", x: 42 };\nconst obj2 = { foo: \"baz\", y: 13 };\nconst mergedObj = { x: 41, ...obj1, ...obj2, y: 9 }; // { x: 42, foo: \"baz\", y: 9 }\nConditionally adding properties to an object\nYou can make an element present or absent in an object literal, depending on a condition, using a conditional operator.\nconst isSummer = false;\nconst fruits = {\napple: 10,\nbanana: 5,\n...(isSummer ? { watermelon: 30 } : {}),\n};\n// { apple: 10, banana: 5 }\nThe case where the condition is false\nis an empty object, so that nothing gets spread into the final object. Note that this is different from the following:\nconst fruits = {\napple: 10,\nbanana: 5,\nwatermelon: isSummer ? 30 : undefined,\n};\n// { apple: 10, banana: 5, watermelon: undefined }\nIn this case, the watermelon\nproperty is always present and will be visited by methods such as Object.keys()\n.\nBecause primitives can be spread into objects as well, and from the observation that all falsy values do not have enumerable properties, you can simply use a logical AND operator:\nconst isSummer = false;\nconst fruits = {\napple: 10,\nbanana: 5,\n...(isSummer && { watermelon: 30 }),\n};\nIn this case, if isSummer\nis any falsy value, no property will be created on the fruits\nobject.\nComparing with Object.assign()\nNote that Object.assign()\ncan be used to mutate an object, whereas spread syntax can't.\nconst obj1 = { foo: \"bar\", x: 42 };\nObject.assign(obj1, { x: 1337 });\nconsole.log(obj1); // { foo: \"bar\", x: 1337 }\nIn addition, Object.assign()\ntriggers setters on the target object, whereas spread syntax does not.\nconst objectAssign = Object.assign(\n{\nset foo(val) {\nconsole.log(val);\n},\n},\n{ foo: 1 },\n);\n// Logs \"1\"; objectAssign.foo is still the original setter\nconst spread = {\nset foo(val) {\nconsole.log(val);\n},\n...{ foo: 1 },\n};\n// Nothing is logged; spread.foo is 1\nYou cannot naively re-implement the Object.assign()\nfunction through a single spreading:\nconst obj1 = { foo: \"bar\", x: 42 };\nconst obj2 = { foo: \"baz\", y: 13 };\nconst merge = (...objects) => ({ ...objects });\nconst mergedObj1 = merge(obj1, obj2);\n// { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } }\nconst mergedObj2 = merge({}, obj1, obj2);\n// { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 13 } }\nIn the above example, the spread syntax does not work as one might expect: it spreads an array of arguments into the object literal, due to the rest parameter. Here is an implementation of merge\nusing the spread syntax, whose behavior is similar to Object.assign()\n, except that it doesn't trigger setters, nor mutates any object:\nconst obj1 = { foo: \"bar\", x: 42 };\nconst obj2 = { foo: \"baz\", y: 13 };\nconst merge = (...objects) =>\nobjects.reduce((acc, cur) => ({ ...acc, ...cur }));\nconst mergedObj = merge(obj1, obj2);\n// { foo: 'baz', x: 42, y: 13 }\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # prod-SpreadElement |\n| ECMAScript\u00ae 2026 Language Specification # prod-ArgumentList |\n| ECMAScript\u00ae 2026 Language Specification # prod-PropertyDefinition |", "code_snippets": ["function sum(x, y, z) {\n return x + y + z;\n}\n\nconst numbers = [1, 2, 3];\n\nconsole.log(sum(...numbers));\n// Expected output: 6\n\nconsole.log(sum.apply(null, numbers));\n// Expected output: 6\n", "myFunction(a, ...iterableObj, b)\n[1, ...iterableObj, '4', 'five', 6]\n{ ...obj, key: 'value' }\n", "const obj = { key1: \"value1\" };\nconst array = [...obj]; // TypeError: obj is not iterable\n", "const array = [1, 2, 3];\nconst obj = { ...array }; // { 0: 1, 1: 2, 2: 3 }\n", "const obj = { ...true, ...\"test\", ...10 };\n// { '0': 't', '1': 'e', '2': 's', '3': 't' }\n", "function myFunction(x, y, z) {}\nconst args = [0, 1, 2];\nmyFunction.apply(null, args);\n", "function myFunction(x, y, z) {}\nconst args = [0, 1, 2];\nmyFunction(...args);\n", "function myFunction(v, w, x, y, z) {}\nconst args = [0, 1];\nmyFunction(-1, ...args, 2, ...[3]);\n", "const dateFields = [1970, 0, 1]; // 1 Jan 1970\nconst d = new Date(...dateFields);\n", "const parts = [\"shoulders\", \"knees\"];\nconst lyrics = [\"head\", ...parts, \"and\", \"toes\"];\n// [\"head\", \"shoulders\", \"knees\", \"and\", \"toes\"]\n", "const arr = [1, 2, 3];\nconst arr2 = [...arr]; // like arr.slice()\n\narr2.push(4);\n// arr2 becomes [1, 2, 3, 4]\n// arr remains unaffected\n", "const a = [[1], [2], [3]];\nconst b = [...a];\n\nb.shift().shift();\n// 1\n\n// Oh no! Now array 'a' is affected as well:\nconsole.log(a);\n// [[], [2], [3]]\n", "let arr1 = [0, 1, 2];\nconst arr2 = [3, 4, 5];\n\n// Append all items from arr2 onto arr1\narr1 = arr1.concat(arr2);\n", "let arr1 = [0, 1, 2];\nconst arr2 = [3, 4, 5];\n\narr1 = [...arr1, ...arr2];\n// arr1 is now [0, 1, 2, 3, 4, 5]\n", "const arr1 = [0, 1, 2];\nconst arr2 = [3, 4, 5];\n\n// Prepend all items from arr2 onto arr1\nArray.prototype.unshift.apply(arr1, arr2);\nconsole.log(arr1); // [3, 4, 5, 0, 1, 2]\n", "let arr1 = [0, 1, 2];\nconst arr2 = [3, 4, 5];\n\narr1 = [...arr2, ...arr1];\nconsole.log(arr1); // [3, 4, 5, 0, 1, 2]\n", "const isSummer = false;\nconst fruits = [\"apple\", \"banana\", ...(isSummer ? [\"watermelon\"] : [])];\n// ['apple', 'banana']\n", "const fruits = [\"apple\", \"banana\", isSummer ? \"watermelon\" : undefined];\n// ['apple', 'banana', undefined]\n", "const obj1 = { foo: \"bar\", x: 42 };\nconst obj2 = { bar: \"baz\", y: 13 };\n\nconst mergedObj = { ...obj1, ...obj2 };\n// { foo: \"bar\", x: 42, bar: \"baz\", y: 13 }\n", "const clonedObj = { ...obj1 };\n// { foo: \"bar\", x: 42 }\n", "const obj1 = { foo: \"bar\", x: 42 };\nconst obj2 = { foo: \"baz\", y: 13 };\n\nconst mergedObj = { x: 41, ...obj1, ...obj2, y: 9 }; // { x: 42, foo: \"baz\", y: 9 }\n", "const isSummer = false;\nconst fruits = {\n apple: 10,\n banana: 5,\n ...(isSummer ? { watermelon: 30 } : {}),\n};\n// { apple: 10, banana: 5 }\n", "const fruits = {\n apple: 10,\n banana: 5,\n watermelon: isSummer ? 30 : undefined,\n};\n// { apple: 10, banana: 5, watermelon: undefined }\n", "const isSummer = false;\nconst fruits = {\n apple: 10,\n banana: 5,\n ...(isSummer && { watermelon: 30 }),\n};\n", "const obj1 = { foo: \"bar\", x: 42 };\nObject.assign(obj1, { x: 1337 });\nconsole.log(obj1); // { foo: \"bar\", x: 1337 }\n", "const objectAssign = Object.assign(\n {\n set foo(val) {\n console.log(val);\n },\n },\n { foo: 1 },\n);\n// Logs \"1\"; objectAssign.foo is still the original setter\n\nconst spread = {\n set foo(val) {\n console.log(val);\n },\n ...{ foo: 1 },\n};\n// Nothing is logged; spread.foo is 1\n", "const obj1 = { foo: \"bar\", x: 42 };\nconst obj2 = { foo: \"baz\", y: 13 };\nconst merge = (...objects) => ({ ...objects });\n\nconst mergedObj1 = merge(obj1, obj2);\n// { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } }\n\nconst mergedObj2 = merge({}, obj1, obj2);\n// { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 13 } }\n", "const obj1 = { foo: \"bar\", x: 42 };\nconst obj2 = { foo: \"baz\", y: 13 };\nconst merge = (...objects) =>\n objects.reduce((acc, cur) => ({ ...acc, ...cur }));\n\nconst mergedObj = merge(obj1, obj2);\n// { foo: 'baz', x: 42, y: 13 }\n"], "language": "JavaScript", "source": "mdn", "token_count": 3557} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/relativetimeformat/index.md\n\n# Original Wiki contributors\nlonglho\nmfuji09\nyairEO\nfscholz\nsideshowbarker\nDmitryMakhnev\nspadgos\nromulocintra\nevilpie\nlittledan\nchrisdavidmills\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 76} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString", "title": "Date.prototype.toTimeString()", "content": "Date.prototype.toTimeString()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe toTimeString()\nmethod of Date\ninstances returns a string representing the time portion of this date interpreted in the local timezone.\nTry it\nconst event = new Date(\"August 19, 1975 23:15:30\");\nconsole.log(event.toTimeString());\n// Expected output: \"23:15:30 GMT+0200 (CEST)\"\n// Note: your timezone may vary\nSyntax\njs\ntoTimeString()\nParameters\nNone.\nReturn value\nA string representing the time portion of the given date (see description for the format). Returns \"Invalid Date\"\nif the date is invalid.\nDescription\nDate\ninstances refer to a specific point in time. toTimeString()\ninterprets the date in the local timezone and formats the time part in English. It always uses the format of HH:mm:ss GMT\u00b1xxxx (TZ)\n, where:\n| Format String | Description |\n|---|---|\nHH |\nHour, as two digits with leading zero if required |\nmm |\nMinute, as two digits with leading zero if required |\nss |\nSeconds, as two digits with leading zero if required |\n\u00b1xxxx |\nThe local timezone's offset \u2014 two digits for hours and two digits for minutes (e.g., -0500 , +0800 ) |\nTZ |\nThe timezone's name (e.g., PDT , PST ) |\nFor example: \"04:42:04 GMT+0000 (Coordinated Universal Time)\".\n- If you only want to get the date part, use\ntoDateString()\n. - If you want to get both the date and time, use\ntoString()\n. - If you want to make the date interpreted as UTC instead of local timezone, use\ntoUTCString()\n. - If you want to format the date in a more user-friendly format (e.g., localization), use\ntoLocaleTimeString()\n.\nExamples\nUsing toTimeString()\njs\nconst d = new Date(0);\nconsole.log(d.toString()); // \"Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)\"\nconsole.log(d.toTimeString()); // \"00:00:00 GMT+0000 (Coordinated Universal Time)\"\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-date.prototype.totimestring |", "code_snippets": ["const event = new Date(\"August 19, 1975 23:15:30\");\n\nconsole.log(event.toTimeString());\n// Expected output: \"23:15:30 GMT+0200 (CEST)\"\n// Note: your timezone may vary\n", "toTimeString()\n", "const d = new Date(0);\n\nconsole.log(d.toString()); // \"Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)\"\nconsole.log(d.toTimeString()); // \"00:00:00 GMT+0000 (Coordinated Universal Time)\"\n"], "language": "JavaScript", "source": "mdn", "token_count": 605} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Duration/toLocaleString", "title": "Temporal.Duration.prototype.toLocaleString()", "content": "Temporal.Duration.prototype.toLocaleString()\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe toLocaleString()\nmethod of Temporal.Duration\ninstances returns a string with a language-sensitive representation of this duration. In implementations with Intl.DurationFormat\nAPI support, this method delegates to Intl.DurationFormat\n.\nEvery time toLocaleString\nis called, it has to perform a search in a big database of localization strings, which is potentially inefficient. When the method is called many times with the same arguments, it is better to create an Intl.DurationFormat\nobject and use its format()\nmethod, because a DurationFormat\nobject remembers the arguments passed to it and may decide to cache a slice of the database, so future format\ncalls can search for localization strings within a more constrained context.\nSyntax\ntoLocaleString()\ntoLocaleString(locales)\ntoLocaleString(locales, options)\nParameters\nThe locales\nand options\nparameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.\nIn implementations that support the Intl.DurationFormat\nAPI, these parameters correspond exactly to the Intl.DurationFormat()\nconstructor's parameters. Implementations without Intl.DurationFormat\nsupport return the exact same string as toString()\n, ignoring both parameters.\nlocales\nOptional-\nA string with a BCP 47 language tag, or an array of such strings. Corresponds to the\nlocales\nparameter of theIntl.DurationFormat()\nconstructor. options\nOptional-\nAn object adjusting the output format. Corresponds to the\noptions\nparameter of theIntl.DurationFormat()\nconstructor.\nSee the Intl.DurationFormat()\nconstructor for details on these parameters and how to use them.\nReturn value\nA string representing the given duration according to language-specific conventions.\nIn implementations with Intl.DurationFormat\n, this is equivalent to new Intl.DurationFormat(locales, options).format(duration)\n.\nNote:\nMost of the time, the formatting returned by toLocaleString()\nis consistent. However, the output may vary between implementations, even within the same locale \u2014 output variations are by design and allowed by the specification. It may also not be what you expect. For example, the string may use non-breaking spaces or be surrounded by bidirectional control characters. You should not compare the results of toLocaleString()\nto hardcoded constants.\nExamples\nUsing toLocaleString()\nBasic use of this method without specifying a locale\nreturns a formatted string in the default locale and with default options.\nconst duration = Temporal.Duration.from({ hours: 1, minutes: 30, seconds: 15 });\nconsole.log(duration.toLocaleString()); // 1 hr, 30 min, 15 sec\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-temporal.duration.prototype.tolocalestring |", "code_snippets": ["toLocaleString()\ntoLocaleString(locales)\ntoLocaleString(locales, options)\n", "const duration = Temporal.Duration.from({ hours: 1, minutes: 30, seconds: 15 });\n\nconsole.log(duration.toLocaleString()); // 1 hr, 30 min, 15 sec\n"], "language": "JavaScript", "source": "mdn", "token_count": 781} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/number/positive_infinity/index.md\n\n# Original Wiki contributors\nmfuji09\nfscholz\nalattalatta\nwbamberg\ndoubleOrt\njameshkramer\nMingun\nAlexChao\nSheppy\nevilpie\nSevenspade\nDiablownik\nMgjbot\nPotappo\nPtak82\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 82} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Reduce_of_empty_array_with_no_initial_value/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.md\n\n# Original Wiki contributors\nfscholz\nlmmfranco\nom-ganesh\nnbp\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 59} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/date/totimestring/index.md\n\n# Original Wiki contributors\nmfuji09\nRobg1\nwbamberg\nfscholz\nr-i-c-h\nschalkneethling\njameshkramer\nschlagi123\neduardoboucas\nMingun\nkscarfone\nSheppy\nethertank\ndtjm\nevilpie\nDikrib\nSevenspade\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 86} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/object/constructor/index.md\n\n# Original Wiki contributors\nkoroliov\nmfuji09\nhinell\nfscholz\nAudaciter\nZearin_Galaurum\nPointy\nalattalatta\nshuped\njonathan-stone\nRobert-Wett\neLeontev\nrivertam\ndd-pardal\nCongelli501\njameshkramer\nsharanvkaur\nastorm\nolegpesok\nMingun\nmbyrne\nAirblader\nSheppy\nGiviKDev\nPaul-Dowsett\nethertank\nevilpie\nkalamay\nSevenspade\nNickolay\nRuakh\nAndrea@3site.it\nMgjbot\nMaian\nMarcoos\nDria\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 131} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_negation", "title": "Unary negation (-)", "content": "Unary negation (-)\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe unary negation (-\n) operator precedes its operand and negates it.\nTry it\nconst x = 4;\nconst y = -x;\nconsole.log(y);\n// Expected output: -4\nconst a = \"4\";\nconst b = -a;\nconsole.log(b);\n// Expected output: -4\nSyntax\njs\n-x\nDescription\nThe -\noperator is overloaded for two types of operands: number and BigInt. It first coerces the operand to a numeric value and tests the type of it. It performs BigInt negation if the operand becomes a BigInt; otherwise, it performs number negation.\nExamples\nNegating numbers\njs\nconst x = 3;\nconst y = -x;\n// y is -3; x is 3\nNegating non-numbers\nThe unary negation operator can convert a non-number into a number.\njs\nconst x = \"4\";\nconst y = -x;\n// y is -4\nBigInts can be negated using the unary negation operator.\njs\nconst x = 4n;\nconst y = -x;\n// y is -4n\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-unary-minus-operator |", "code_snippets": ["const x = 4;\nconst y = -x;\n\nconsole.log(y);\n// Expected output: -4\n\nconst a = \"4\";\nconst b = -a;\n\nconsole.log(b);\n// Expected output: -4\n", "-x\n", "const x = 3;\nconst y = -x;\n// y is -3; x is 3\n", "const x = \"4\";\nconst y = -x;\n\n// y is -4\n", "const x = 4n;\nconst y = -x;\n\n// y is -4n\n"], "language": "JavaScript", "source": "mdn", "token_count": 338} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY", "title": "Number.NEGATIVE_INFINITY", "content": "Number.NEGATIVE_INFINITY\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe Number.NEGATIVE_INFINITY\nstatic data property represents the negative Infinity value.\nTry it\nfunction checkNumber(smallNumber) {\nif (smallNumber === Number.NEGATIVE_INFINITY) {\nreturn \"Process number as -Infinity\";\n}\nreturn smallNumber;\n}\nconsole.log(checkNumber(-Number.MAX_VALUE));\n// Expected output: -1.7976931348623157e+308\nconsole.log(checkNumber(-Number.MAX_VALUE * 2));\n// Expected output: \"Process number as -Infinity\"\nValue\nThe same as the negative value of the global Infinity\nproperty.\nProperty attributes of Number.NEGATIVE_INFINITY | |\n|---|---|\n| Writable | no |\n| Enumerable | no |\n| Configurable | no |\nDescription\nThe Number.NEGATIVE_INFINITY\nvalue behaves slightly differently than mathematical infinity:\n- Any positive value, including\nPOSITIVE_INFINITY\n, multiplied byNEGATIVE_INFINITY\nisNEGATIVE_INFINITY\n. - Any negative value, including\nNEGATIVE_INFINITY\n, multiplied byNEGATIVE_INFINITY\nisPOSITIVE_INFINITY\n. - Any positive value divided by\nNEGATIVE_INFINITY\nis negative zero (as defined in IEEE 754). - Any negative value divided by\nNEGATIVE_INFINITY\nis positive zero (as defined in IEEE 754). - Zero multiplied by\nNEGATIVE_INFINITY\nisNaN\n. NaN\nmultiplied byNEGATIVE_INFINITY\nisNaN\n.NEGATIVE_INFINITY\n, divided by any negative value exceptNEGATIVE_INFINITY\n, isPOSITIVE_INFINITY\n.NEGATIVE_INFINITY\n, divided by any positive value exceptPOSITIVE_INFINITY\n, isNEGATIVE_INFINITY\n.NEGATIVE_INFINITY\n, divided by eitherNEGATIVE_INFINITY\norPOSITIVE_INFINITY\n, isNaN\n.x > Number.NEGATIVE_INFINITY\nis true for any number x that isn'tNEGATIVE_INFINITY\n.\nYou might use the Number.NEGATIVE_INFINITY\nproperty to indicate an error condition that returns a finite number in case of success. Note, however, that NaN\nwould be more appropriate in such a case.\nBecause NEGATIVE_INFINITY\nis a static property of Number\n, you always use it as Number.NEGATIVE_INFINITY\n, rather than as a property of a number value.\nExamples\nUsing NEGATIVE_INFINITY\nIn the following example, the variable smallNumber\nis assigned a value that is smaller than the minimum value. When the if\nstatement executes, smallNumber\nhas the value -Infinity\n, so smallNumber\nis set to a more manageable value before continuing.\nlet smallNumber = -Number.MAX_VALUE * 2;\nif (smallNumber === Number.NEGATIVE_INFINITY) {\nsmallNumber = returnFinite();\n}\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-number.negative_infinity |", "code_snippets": ["function checkNumber(smallNumber) {\n if (smallNumber === Number.NEGATIVE_INFINITY) {\n return \"Process number as -Infinity\";\n }\n return smallNumber;\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 smallNumber = -Number.MAX_VALUE * 2;\n\nif (smallNumber === Number.NEGATIVE_INFINITY) {\n smallNumber = returnFinite();\n}\n"], "language": "JavaScript", "source": "mdn", "token_count": 775} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/object/propertyisenumerable/index.md\n\n# Original Wiki contributors\nchrisdavidmills\nvkweb\nalextaghavi\nmfuji09\nwbamberg\nfscholz\nKinL\nrileym7\njameshkramer\nSebastianz\neduardoboucas\nMingun\nSheppy\nBrettz9\nethertank\nevilpie\ndofusion\nMgjbot\nSevenspade\nWaldo\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 94} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/valueOf", "title": "Number.prototype.valueOf()", "content": "Number.prototype.valueOf()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe valueOf()\nmethod of Number\nvalues returns the value of this number.\nTry it\nconst numObj = new Number(42);\nconsole.log(typeof numObj);\n// Expected output: \"object\"\nconst num = numObj.valueOf();\nconsole.log(num);\n// Expected output: 42\nconsole.log(typeof num);\n// Expected output: \"number\"\nSyntax\njs\nvalueOf()\nParameters\nNone.\nReturn value\nA number representing the primitive value of the specified Number\nobject.\nDescription\nThis method is usually called internally by JavaScript and not explicitly in web code.\nExamples\nUsing valueOf\njs\nconst numObj = new Number(10);\nconsole.log(typeof numObj); // object\nconst num = numObj.valueOf();\nconsole.log(num); // 10\nconsole.log(typeof num); // number\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-number.prototype.valueof |", "code_snippets": ["const numObj = new Number(42);\nconsole.log(typeof numObj);\n// Expected output: \"object\"\n\nconst num = numObj.valueOf();\nconsole.log(num);\n// Expected output: 42\n\nconsole.log(typeof num);\n// Expected output: \"number\"\n", "valueOf()\n", "const numObj = new Number(10);\nconsole.log(typeof numObj); // object\n\nconst num = numObj.valueOf();\nconsole.log(num); // 10\nconsole.log(typeof num); // number\n"], "language": "JavaScript", "source": "mdn", "token_count": 346} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString", "title": "Array.prototype.toString()", "content": "Array.prototype.toString()\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe toString()\nmethod of Array\ninstances returns a string representing the\nspecified array and its elements.\nTry it\nconst array = [1, 2, \"a\", \"1a\"];\nconsole.log(array.toString());\n// Expected output: \"1,2,a,1a\"\nSyntax\ntoString()\nParameters\nNone.\nReturn value\nA string representing the elements of the array.\nDescription\nThe Array\nobject overrides the toString\nmethod of Object\n. The toString\nmethod of arrays calls join()\ninternally, which joins the array and returns one string containing each array element separated by commas. If the join\nmethod is unavailable or is not a function, Object.prototype.toString\nis used instead, returning [object Array]\n.\nconst arr = [];\narr.join = 1; // re-assign `join` with a non-function\nconsole.log(arr.toString()); // [object Array]\nconsole.log(Array.prototype.toString.call({ join: () => 1 })); // 1\nJavaScript calls the toString\nmethod automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.\nArray.prototype.toString\nrecursively converts each element, including other arrays, to strings. Because the string returned by Array.prototype.toString\ndoes not have delimiters, nested arrays look like they are flattened.\nconst matrix = [\n[1, 2, 3],\n[4, 5, 6],\n[7, 8, 9],\n];\nconsole.log(matrix.toString()); // 1,2,3,4,5,6,7,8,9\nWhen an array is cyclic (it contains an element that is itself), browsers avoid infinite recursion by ignoring the cyclic reference.\nconst arr = [];\narr.push(1, [3, arr, 4], 2);\nconsole.log(arr.toString()); // 1,3,,4,2\nExamples\nUsing toString()\nconst array = [1, 2, \"a\", \"1a\"];\nconsole.log(array.toString()); // \"1,2,a,1a\"\nUsing toString() on sparse arrays\nFollowing the behavior of join()\n, toString()\ntreats empty slots the same as undefined\nand produces an extra separator:\nconsole.log([1, , 3].toString()); // '1,,3'\nCalling toString() on non-array objects\ntoString()\nis generic. It expects this\nto have a join()\nmethod; or, failing that, uses Object.prototype.toString()\ninstead.\nconsole.log(Array.prototype.toString.call({ join: () => 1 }));\n// 1; a number\nconsole.log(Array.prototype.toString.call({ join: () => undefined }));\n// undefined\nconsole.log(Array.prototype.toString.call({ join: \"not function\" }));\n// \"[object Object]\"\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-array.prototype.tostring |", "code_snippets": ["const array = [1, 2, \"a\", \"1a\"];\n\nconsole.log(array.toString());\n// Expected output: \"1,2,a,1a\"\n", "toString()\n", "const arr = [];\narr.join = 1; // re-assign `join` with a non-function\nconsole.log(arr.toString()); // [object Array]\n\nconsole.log(Array.prototype.toString.call({ join: () => 1 })); // 1\n", "const matrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n];\n\nconsole.log(matrix.toString()); // 1,2,3,4,5,6,7,8,9\n", "const arr = [];\narr.push(1, [3, arr, 4], 2);\nconsole.log(arr.toString()); // 1,3,,4,2\n", "const array = [1, 2, \"a\", \"1a\"];\n\nconsole.log(array.toString()); // \"1,2,a,1a\"\n", "console.log([1, , 3].toString()); // '1,,3'\n", "console.log(Array.prototype.toString.call({ join: () => 1 }));\n// 1; a number\nconsole.log(Array.prototype.toString.call({ join: () => undefined }));\n// undefined\nconsole.log(Array.prototype.toString.call({ join: \"not function\" }));\n// \"[object Object]\"\n"], "language": "JavaScript", "source": "mdn", "token_count": 860} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift_assignment", "title": "Right shift assignment (>>=)", "content": "Right shift assignment (>>=)\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since July 2015.\nThe right shift assignment (>>=\n) operator performs right shift on the two operands and assigns the result to the left operand.\nTry it\nlet a = 5; // 00000000000000000000000000000101\na >>= 2; // 00000000000000000000000000000001\nconsole.log(a);\n// Expected output: 1\nlet b = -5; // 11111111111111111111111111111011\nb >>= 2; // 11111111111111111111111111111110\nconsole.log(b);\n// Expected output: -2\nSyntax\njs\nx >>= y\nDescription\nx >>= y\nis equivalent to x = x >> y\n, except that the expression x\nis only evaluated once.\nExamples\nUsing right shift assignment\njs\nlet a = 5; // (00000000000000000000000000000101)\na >>= 2; // 1 (00000000000000000000000000000001)\nlet b = -5; // (-00000000000000000000000000000101)\nb >>= 2; // -2 (-00000000000000000000000000000010)\nlet c = 5n;\nc >>= 2n; // 1n\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-assignment-operators |", "code_snippets": ["let a = 5; // 00000000000000000000000000000101\n\na >>= 2; // 00000000000000000000000000000001\nconsole.log(a);\n// Expected output: 1\n\nlet b = -5; // 11111111111111111111111111111011\n\nb >>= 2; // 11111111111111111111111111111110\nconsole.log(b);\n// Expected output: -2\n", "x >>= y\n", "let a = 5; // (00000000000000000000000000000101)\na >>= 2; // 1 (00000000000000000000000000000001)\n\nlet b = -5; // (-00000000000000000000000000000101)\nb >>= 2; // -2 (-00000000000000000000000000000010)\n\nlet c = 5n;\nc >>= 2n; // 1n\n"], "language": "JavaScript", "source": "mdn", "token_count": 400} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat/format/index.md\n\n# Original Wiki contributors\nmfuji09\nfscholz\nwbamberg\nsideshowbarker\nSphinxKnight\nbattaglr\nchrisdavidmills\narai\nDavid_Gilbertson\nMingun\nSheppy\nNorbert\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 79} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/numberformat/numberformat/index.md\n\n# Original Wiki contributors\nromulocintra\nmfuji09\nfscholz\nacontreras89\nwbamberg\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 62} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/No_properties/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/errors/no_properties/index.md\n\n# Original Wiki contributors\nfscholz\nPatrickKettner\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 49} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/resolvedOptions/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/numberformat/resolvedoptions/index.md\n\n# Original Wiki contributors\nfscholz\nsideshowbarker\nbkardell\nbattaglr\nwbamberg\narai\nDavid_Gilbertson\neduardoboucas\nMingun\nSheppy\nNorbert\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 77} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Execution_model/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/execution_model/index.md\n\n# Original Wiki contributors\nfscholz\nBoQsc\nvegerot\nwbamberg\nPierBover\nZearin_Galaurum\nSheppy\ndivyanshu013\nSphinxKnight\nAnkitaSood\nolegolegoleg\neyalChistik\nmetasean\nMadEmperorYuri\nharminho\nPeiren\npirtleshell\nantunmagdic\nadrianosmond\ndoubleOrt\nutkarshbhatt12\nJun711\naminoche\nstephaniehobson\nsautumn\nsturmer\ncoolarun\nperryjiang\nbroAhmed\nroryokane\nnmve\nMartin-Ting\nonurtemizkan\nkeshvari\njxjj\nmprogers\nnikjohn\nraeesiqbal\nmasthandev\namilajack\ninglor\nhanu412\njswisher\nPortableStick\nsuhajdab\nkscarfone\nchakkakuru\nEddieFloresLive\ndbruant\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 167} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag", "title": "Symbol.toStringTag", "content": "Symbol.toStringTag\nBaseline\nWidely available\nThis feature is well established and works across many devices and browser versions. It\u2019s been available across browsers since April 2017.\nThe Symbol.toStringTag\nstatic data property represents the well-known symbol Symbol.toStringTag\n. Object.prototype.toString()\nlooks up this symbol on the this\nvalue for the property containing a string that represents the type of the object.\nTry it\nclass ValidatorClass {\nget [Symbol.toStringTag]() {\nreturn \"Validator\";\n}\n}\nconsole.log(Object.prototype.toString.call(new ValidatorClass()));\n// Expected output: \"[object Validator]\"\nValue\nThe well-known symbol Symbol.toStringTag\n.\nProperty attributes of Symbol.toStringTag | |\n|---|---|\n| Writable | no |\n| Enumerable | no |\n| Configurable | no |\nExamples\nDefault tags\nSome values do not have Symbol.toStringTag\n, but have special toString()\nrepresentations. For a complete list, see Object.prototype.toString()\n.\nObject.prototype.toString.call(\"foo\"); // \"[object String]\"\nObject.prototype.toString.call([1, 2]); // \"[object Array]\"\nObject.prototype.toString.call(3); // \"[object Number]\"\nObject.prototype.toString.call(true); // \"[object Boolean]\"\nObject.prototype.toString.call(undefined); // \"[object Undefined]\"\nObject.prototype.toString.call(null); // \"[object Null]\"\n// \u2026 and more\nBuilt-in toStringTag symbols\nMost built-in objects provide their own [Symbol.toStringTag]\nproperty. Almost all built-in objects' [Symbol.toStringTag]\nproperty is not writable, not enumerable, and configurable; the exception is Iterator\n, which is writable for compatibility reasons.\nFor constructor objects like Promise\n, the property is installed on Constructor.prototype\n, so that all instances of the constructor inherit [Symbol.toStringTag]\nand can be stringified. For non-constructor objects like Math\nand JSON\n, the property is installed as a static property, so that the namespace object itself can be stringified. Sometimes, the constructor also provides its own toString\nmethod (for example, Intl.Locale\n), in which case the [Symbol.toStringTag]\nproperty is only used when you explicitly call Object.prototype.toString\non it.\nObject.prototype.toString.call(new Map()); // \"[object Map]\"\nObject.prototype.toString.call(function* () {}); // \"[object GeneratorFunction]\"\nObject.prototype.toString.call(Promise.resolve()); // \"[object Promise]\"\n// \u2026 and more\nCustom tag with toStringTag\nWhen creating your own class, JavaScript defaults to the \"Object\" tag:\nclass ValidatorClass {}\nObject.prototype.toString.call(new ValidatorClass()); // \"[object Object]\"\nNow, with the help of toStringTag\n, you are able to set your own custom tag:\nclass ValidatorClass {\nget [Symbol.toStringTag]() {\nreturn \"Validator\";\n}\n}\nObject.prototype.toString.call(new ValidatorClass()); // \"[object Validator]\"\ntoStringTag available on all DOM prototype objects\nDue to a WebIDL spec change in mid-2020, browsers are adding a Symbol.toStringTag\nproperty to all DOM prototype objects. For example, to access the Symbol.toStringTag\nproperty on HTMLButtonElement\n:\nconst test = document.createElement(\"button\");\ntest.toString(); // \"[object HTMLButtonElement]\"\ntest[Symbol.toStringTag]; // \"HTMLButtonElement\"\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-symbol.tostringtag |", "code_snippets": ["class ValidatorClass {\n get [Symbol.toStringTag]() {\n return \"Validator\";\n }\n}\n\nconsole.log(Object.prototype.toString.call(new ValidatorClass()));\n// Expected output: \"[object Validator]\"\n", "Object.prototype.toString.call(\"foo\"); // \"[object String]\"\nObject.prototype.toString.call([1, 2]); // \"[object Array]\"\nObject.prototype.toString.call(3); // \"[object Number]\"\nObject.prototype.toString.call(true); // \"[object Boolean]\"\nObject.prototype.toString.call(undefined); // \"[object Undefined]\"\nObject.prototype.toString.call(null); // \"[object Null]\"\n// \u2026 and more\n", "Object.prototype.toString.call(new Map()); // \"[object Map]\"\nObject.prototype.toString.call(function* () {}); // \"[object GeneratorFunction]\"\nObject.prototype.toString.call(Promise.resolve()); // \"[object Promise]\"\n// \u2026 and more\n", "class ValidatorClass {}\n\nObject.prototype.toString.call(new ValidatorClass()); // \"[object Object]\"\n", "class ValidatorClass {\n get [Symbol.toStringTag]() {\n return \"Validator\";\n }\n}\n\nObject.prototype.toString.call(new ValidatorClass()); // \"[object Validator]\"\n", "const test = document.createElement(\"button\");\ntest.toString(); // \"[object HTMLButtonElement]\"\ntest[Symbol.toStringTag]; // \"HTMLButtonElement\"\n"], "language": "JavaScript", "source": "mdn", "token_count": 1130} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Duration/years/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/temporal/duration/years/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 40} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/formatToParts", "title": "Intl.DurationFormat.prototype.formatToParts()", "content": "Intl.DurationFormat.prototype.formatToParts()\nBaseline\n2025\nNewly available\nSince March 2025, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.\nThe formatToParts()\nmethod of Intl.DurationFormat\ninstances returns an array of objects representing each part of the formatted string that would be returned by format()\n. It is useful for building custom strings from the locale-specific tokens.\nSyntax\nformatToParts(duration)\nParameters\nduration\nOptional-\nThe duration object to be formatted. It should include some or all of the following properties:\nyears\n,months\n,weeks\n,days\n,hours\n,minutes\n,seconds\n,milliseconds\n,microseconds\n,nanoseconds\n. Each property's value should be an integer, and their signs should be consistent. This can be aTemporal.Duration\nobject; see theTemporal.Duration\ndocumentation for more information about these properties.\nReturn value\nAn Array\nof objects containing the formatted duration in parts. Each object has two or three properties, type\n, value\n, and optionally unit\n, each containing a string. The string concatenation of value\n, in the order provided, will result in the same string as format()\n. The parts can be thought of as directly obtained from calling Intl.NumberFormat.prototype.formatToParts()\nwith the numeric value and their respective units. All tokens that are produced by the NumberFormat\nhave an additional unit\nproperty, which is the singular form of the input unit\n; this is for programmatic usage and is not localized. The localized unit is output as a separate unit\ntoken as part of the NumberFormat\nresult. The parts from each duration unit are concatenated together in the same fashion as calling Intl.ListFormat.prototype.formatToParts()\nwith { type: \"unit\" }\n, so additional literal tokens are inserted.\nExamples\nThe formatToParts\nmethod enables locale-aware formatting of strings produced by DurationFormat\nformatters by providing you the string in parts:\nconst duration = {\nhours: 7,\nminutes: 8,\nseconds: 9,\nmilliseconds: 123,\nmicroseconds: 456,\nnanoseconds: 789,\n};\nnew Intl.DurationFormat(\"en\", { style: \"long\" }).formatToParts(duration);\n// Returned value:\n[\n{ type: \"integer\", value: \"7\", unit: \"hour\" },\n{ type: \"literal\", value: \" \", unit: \"hour\" },\n{ type: \"unit\", value: \"hours\", unit: \"hour\" },\n{ type: \"literal\", value: \", \" },\n{ type: \"integer\", value: \"8\", unit: \"minute\" },\n{ type: \"literal\", value: \" \", unit: \"minute\" },\n{ type: \"unit\", value: \"minutes\", unit: \"minute\" },\n{ type: \"literal\", value: \", \" },\n{ type: \"integer\", value: \"9\", unit: \"second\" },\n{ type: \"literal\", value: \" \", unit: \"second\" },\n{ type: \"unit\", value: \"seconds\", unit: \"second\" },\n{ type: \"literal\", value: \", \" },\n{ type: \"integer\", value: \"123\", unit: \"millisecond\" },\n{ type: \"literal\", value: \" \", unit: \"millisecond\" },\n{ type: \"unit\", value: \"milliseconds\", unit: \"millisecond\" },\n{ type: \"literal\", value: \", \" },\n{ type: \"integer\", value: \"456\", unit: \"microsecond\" },\n{ type: \"literal\", value: \" \", unit: \"microsecond\" },\n{ type: \"unit\", value: \"microseconds\", unit: \"microsecond\" },\n{ type: \"literal\", value: \", \" },\n{ type: \"integer\", value: \"789\", unit: \"nanosecond\" },\n{ type: \"literal\", value: \" \", unit: \"nanosecond\" },\n{ type: \"unit\", value: \"nanoseconds\", unit: \"nanosecond\" },\n];\nSpecifications\n| Specification |\n|---|\n| Intl.DurationFormat # sec-Intl.DurationFormat.prototype.formatToParts |", "code_snippets": ["formatToParts(duration)\n", "const duration = {\n hours: 7,\n minutes: 8,\n seconds: 9,\n milliseconds: 123,\n microseconds: 456,\n nanoseconds: 789,\n};\n\nnew Intl.DurationFormat(\"en\", { style: \"long\" }).formatToParts(duration);\n\n// Returned value:\n[\n { type: \"integer\", value: \"7\", unit: \"hour\" },\n { type: \"literal\", value: \" \", unit: \"hour\" },\n { type: \"unit\", value: \"hours\", unit: \"hour\" },\n { type: \"literal\", value: \", \" },\n { type: \"integer\", value: \"8\", unit: \"minute\" },\n { type: \"literal\", value: \" \", unit: \"minute\" },\n { type: \"unit\", value: \"minutes\", unit: \"minute\" },\n { type: \"literal\", value: \", \" },\n { type: \"integer\", value: \"9\", unit: \"second\" },\n { type: \"literal\", value: \" \", unit: \"second\" },\n { type: \"unit\", value: \"seconds\", unit: \"second\" },\n { type: \"literal\", value: \", \" },\n { type: \"integer\", value: \"123\", unit: \"millisecond\" },\n { type: \"literal\", value: \" \", unit: \"millisecond\" },\n { type: \"unit\", value: \"milliseconds\", unit: \"millisecond\" },\n { type: \"literal\", value: \", \" },\n { type: \"integer\", value: \"456\", unit: \"microsecond\" },\n { type: \"literal\", value: \" \", unit: \"microsecond\" },\n { type: \"unit\", value: \"microseconds\", unit: \"microsecond\" },\n { type: \"literal\", value: \", \" },\n { type: \"integer\", value: \"789\", unit: \"nanosecond\" },\n { type: \"literal\", value: \" \", unit: \"nanosecond\" },\n { type: \"unit\", value: \"nanoseconds\", unit: \"nanosecond\" },\n];\n"], "language": "JavaScript", "source": "mdn", "token_count": 1213} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Duration/years", "title": "Temporal.Duration.prototype.years", "content": "Temporal.Duration.prototype.years\nLimited availability\nThis feature is not Baseline because it does not work in some of the most widely-used browsers.\nThe years\naccessor property of Temporal.Duration\ninstances returns an integer representing the number of years in the duration.\nYou can know the sign of years\nby checking the duration's sign\nproperty.\nThe set accessor of years\nis undefined\n. You cannot change this property directly. Use the with()\nmethod to create a new Temporal.Duration\nobject with the desired new value.\nExamples\nUsing years\njs\nconst d1 = Temporal.Duration.from({ years: 1, months: 1 });\nconst d2 = Temporal.Duration.from({ years: -1, months: -1 });\nconst d3 = Temporal.Duration.from({ years: 1 });\nconst d4 = Temporal.Duration.from({ months: 12 });\nconsole.log(d1.years); // 1\nconsole.log(d2.years); // -1\nconsole.log(d3.years); // 1\nconsole.log(d4.years); // 0\n// Balance d4\nconst d4Balanced = d4.round({\nlargestUnit: \"years\",\nrelativeTo: Temporal.PlainDate.from(\"2021-01-01\"), // ISO 8601 calendar\n});\nconsole.log(d4Balanced.years); // 1\nconsole.log(d4Balanced.months); // 0\nSpecifications\n| Specification |\n|---|\n| Temporal # sec-get-temporal.duration.prototype.years |\nBrowser compatibility\nSee also\nTemporal.Duration\nTemporal.Duration.prototype.months\nTemporal.Duration.prototype.weeks\nTemporal.Duration.prototype.days\nTemporal.Duration.prototype.hours\nTemporal.Duration.prototype.minutes\nTemporal.Duration.prototype.seconds\nTemporal.Duration.prototype.milliseconds\nTemporal.Duration.prototype.microseconds\nTemporal.Duration.prototype.nanoseconds", "code_snippets": ["const d1 = Temporal.Duration.from({ years: 1, months: 1 });\nconst d2 = Temporal.Duration.from({ years: -1, months: -1 });\nconst d3 = Temporal.Duration.from({ years: 1 });\nconst d4 = Temporal.Duration.from({ months: 12 });\n\nconsole.log(d1.years); // 1\nconsole.log(d2.years); // -1\nconsole.log(d3.years); // 1\nconsole.log(d4.years); // 0\n\n// Balance d4\nconst d4Balanced = d4.round({\n largestUnit: \"years\",\n relativeTo: Temporal.PlainDate.from(\"2021-01-01\"), // ISO 8601 calendar\n});\nconsole.log(d4Balanced.years); // 1\nconsole.log(d4Balanced.months); // 0\n"], "language": "JavaScript", "source": "mdn", "token_count": 532} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/iteration_protocols/index.md\n\n# Original Wiki contributors\ndd-pardal\nsinanergin\nmfuji09\nRainSlide\nfscholz\ntim_cannon\nZearin_Galaurum\nwbamberg\nKennethKinLum\nGKJCJG\ndmitryrn\njuraj\nSIMON-Yann\nconartist6\nkdex\njackblackevo\nRobg1\nstephaniehobson\nyackSpillsaps\nLandmaster\nrwaldron\nCodeFry\nmamacdon\nwedaren\nmksarge\nXMO\nbcherny\nnmve\nDarylPinto\njsbisht\nDelapouite\ndanwellman\nAshCoolman\nteoli\nNickolay\nstevekinney\narai\nicold\nSphinxKnight\nziyunfei\nKevinLozandier\ndbruant\nHavvy\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 144} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/function/length/index.md\n\n# Original Wiki contributors\nmfuji09\nfscholz\njpmedley\nSphinxKnight\nnaveenrawat51\nGwyn\nwbamberg\njameshkramer\nwuct\nJeremie\njulienq\nMingun\nSheppy\nshizm46\nethertank\nevilpie\ntrevorh\nziyunfei\nSevenspade\nmathiasbynens\nBrettz9\nMgjbot\nMaian\nDria\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 98} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Symbol.unscopables", "title": "Array.prototype[Symbol.unscopables]", "content": "Array.prototype[Symbol.unscopables]\nThe [Symbol.unscopables]\ndata property of Array.prototype\nis shared by all Array\ninstances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for with\nstatement-binding purposes.\nValue\nA null\n-prototype object with property names given below and their values set to true\n.\nProperty attributes of Array.prototype[Symbol.unscopables] | |\n|---|---|\n| Writable | no |\n| Enumerable | no |\n| Configurable | yes |\nDescription\nThe default Array\nproperties that are ignored for with\nstatement-binding purposes are:\nat()\ncopyWithin()\nentries()\nfill()\nfind()\nfindIndex()\nfindLast()\nfindLastIndex()\nflat()\nflatMap()\nincludes()\nkeys()\ntoReversed()\ntoSorted()\ntoSpliced()\nvalues()\nArray.prototype[Symbol.unscopables]\nis an empty object only containing all the above property names with the value true\n. Its prototype is null\n, so Object.prototype\nproperties like toString\nwon't accidentally be made unscopable, and a toString()\nwithin the with\nstatement will continue to be called on the array.\nSee Symbol.unscopables\nfor how to set unscopable properties for your own objects.\nExamples\nImagine the values.push('something')\ncall below is in code that was written prior to ECMAScript 2015.\nvar values = [];\nwith (values) {\nvalues.push(\"something\");\n}\nWhen ECMAScript 2015 introduced the Array.prototype.values()\nmethod, the with\nstatement in the above code started to interpret values\nas the values.values\narray method instead of the external values\nvariable. The values.push('something')\ncall would break because it's now accessing push\non the values.values\nmethod. This caused a bug to be reported to Firefox (Firefox Bug 883914).\nSo the [Symbol.unscopables]\ndata property for Array.prototype\ncauses the Array\nproperties introduced in ECMAScript 2015 to be ignored for with\nstatement-binding purposes \u2014 allowing code that was written prior to ECMAScript 2015 to continue working as expected, rather than breaking.\nSpecifications\n| Specification |\n|---|\n| ECMAScript\u00ae 2026 Language Specification # sec-array.prototype-%symbol.unscopables% |", "code_snippets": ["var values = [];\n\nwith (values) {\n values.push(\"something\");\n}\n"], "language": "JavaScript", "source": "mdn", "token_count": 550} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/supportedLocalesOf/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/numberformat/supportedlocalesof/index.md\n\n# Original Wiki contributors\nmfuji09\nfscholz\nwbamberg\nsideshowbarker\nbattaglr\narai\neduardoboucas\nMingun\nSheppy\nNorbert\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 73} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/format/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/intl/listformat/format/index.md\n\n# Original Wiki contributors\nmfuji09\nwbamberg\nfscholz\nbrian_\nSphinxKnight\nsenna\nrwe2020\nsideshowbarker\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 66} +{"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Requires_global_RegExp/contributors.txt", "title": null, "content": "# Contributors by commit history\nhttps://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/errors/requires_global_regexp/index.md\n\n", "code_snippets": [], "language": "JavaScript", "source": "mdn", "token_count": 38}