Intl.ListFormat.prototype.resolvedOptions()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2021.
The resolvedOptions()
method of Intl.ListFormat
instances returns a new object with properties reflecting the options computed during initialization of this ListFormat
object.
Try it
const deListFormatter = new Intl.ListFormat("de-DE", { type: "disjunction" });
const options = deListFormatter.resolvedOptions();
console.log(options.locale);
// Expected output: "de-DE"
console.log(options.style);
// Expected output: "long"
console.log(options.type);
// Expected output: "disjunction"
Syntax
resolvedOptions()
Parameters
None.
Return value
A new object with properties reflecting the options computed during the initialization of this ListFormat
object. The object has the following properties, in the order they are listed:
locale
-
The 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.
type
-
The value provided for this property in the
options
argument, with default filled in as needed. It is either"conjunction"
,"disjunction"
, or"unit"
. The default is"conjunction"
. style
-
The value provided for this property in the
options
argument, with default filled in as needed. It is either"long"
,"short"
, or"narrow"
. The default is"long"
.
Examples
Using resolvedOptions
const deListFormatter = new Intl.ListFormat("de-DE", { style: "short" });
const usedOptions = de.resolvedOptions();
console.log(usedOptions.locale); // "de-DE"
console.log(usedOptions.style); // "short"
console.log(usedOptions.type); // "conjunction" (the default value)
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # sec-Intl.ListFormat.prototype.resolvedoptions |


Function: name

Function: name
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since August 2016.
The name
data property of a Function
instance indicates the function's name as specified when it was created, or it may be either anonymous
or ''
(an empty string) for functions created anonymously.
Try it
const func1 = function () {};
const object = {
func2: function () {},
};
console.log(func1.name);
// Expected output: "func1"
console.log(object.func2.name);
// Expected output: "func2"
Value
A string.
Property attributes of Function: name | |
|---|---|
| Writable | no |
| Enumerable | no |
| Configurable | yes |
Note:
In non-standard, pre-ES2015 implementations the configurable
attribute was false
as well.
Description
The function's name
property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself.
The name
property is read-only and cannot be changed by the assignment operator:
function someFunction() {}
someFunction.name = "otherFunction";
console.log(someFunction.name); // someFunction
To change it, use Object.defineProperty()
.
The name
property 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.
Function declaration
The name
property returns the name of a function declaration.
function doSomething() {}
doSomething.name; // "doSomething"
Default-exported function declaration
An export default
declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is "default"
.
// -- someModule.js --
export default function () {}
// -- main.js --
import someModule from "./someModule.js";
someModule.name; // "default"
Function constructor
Functions created with the Function()
constructor have name "anonymous".
new Function().name; // "anonymous"
Function expression
If the function expression is named, that name is used as the name
property.
const someFunction = function someFunctionName() {};
someFunction.name; // "someFunctionName"
Anonymous function expressions, created using either the function
keyword or the arrow function syntax, have ""
(an empty string) as their name by default.
(function () {}).name; // ""
(() => {}).name; // ""
However, such cases are rare — 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.
One practical case where the name cannot be inferred is a function returned from another function:
function getFoo() {
return () => {};
}
getFoo().name; // ""
Variable declaration and method
Variables and methods can infer the name of an anonymous function from its syntactic position.
const f = function () {};
const object = {
someMethod: function () {},
};
console.log(f.name); // "f"
console.log(object.someMethod.name); // "someMethod"
The same applies to assignment:
let f;
f = () => {};
f.name; // "f"
Initializer and default value
Functions in initializers (default values) of destructuring, default parameters, class fields, etc., will inherit the name of the bound identifier as their name
.
const [f = () => {}] = [];
f.name; // "f"
const { someMethod: m = () => {} } = {};
m.name; // "m"
function foo(f = () => {}) {
console.log(f.name);
}
foo(); // "f"
class Foo {
static someMethod = () => {};
}
Foo.someMethod.name; // someMethod
Shorthand method
const o = {
foo() {},
};
o.foo.name; // "foo";
Bound function
Function.prototype.bind()
produces a function whose name is "bound " plus the function name.
function foo() {}
foo.bind({}).name; // "bound foo"
Getter and setter
When using get
and set
accessor properties, "get" or "set" will appear in the function name.
const o = {
get foo() {
return 1;
},
set foo(x) {},
};
const descriptor = Object.getOwnPropertyDescriptor(o, "foo");
descriptor.get.name; // "get foo"
descriptor.set.name; // "set foo";
Class
A class's name follows the same algorithm as function declarations and expressions.
class Foo {}
Foo.name; // "Foo"
Warning:
JavaScript will set the function's name
property only if a function does not have an own property called name
. However, classes' static members will be set as own properties of the class constructor function, and thus prevent the built-in name
from being applied. See an example below.
Symbol as function name
If a Symbol
is used a function name and the symbol has a description, the method's name is the description in square brackets.
const sym1 = Symbol("foo");
const sym2 = Symbol();
const o = {
[sym1]() {},
[sym2]() {},
};
o[sym1].name; // "[foo]"
o[sym2].name; // "[]"
Private fields and methods
Private fields and private methods have the hash (#
) as part of their names.
class Foo {
#field = () => {};
#method() {}
getNames() {
console.log(this.#field.name);
console.log(this.#method.name);
}
}
new Foo().getNames();
// "#field"
// "#method"
Examples
Telling the constructor name of an object
You can use obj.constructor.name
to check the "class" of an object.
function Foo() {} // Or: class Foo {}
const fooInstance = new Foo();
console.log(fooInstance.constructor.name); // "Foo"
However, 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()
:
class Foo {
constructor() {}
static name() {}
}
With a static name()
method Foo.name
no longer holds the actual class name but a reference to the name()
function object. Trying to obtain the class of fooInstance
via fooInstance.constructor.name
won't give us the class name at all, but instead a reference to the static class method. Example:
const fooInstance = new Foo();
console.log(fooInstance.constructor.name); // ƒ name() {}
Due to the existence of static fields, name
may not be a function either.
class Foo {
static name = 123;
}
console.log(new Foo().constructor.name); // 123
If a class has a static property called name
, it will also become writable. The built-in definition in the absence of a custom static definition is read-only:
Foo.name = "Hello";
console.log(Foo.name); // "Hello" if class Foo has a static "name" property, but "Foo" if not.
Therefore you may not rely on the built-in name
property to always hold a class's name.
JavaScript compressors and minifiers
Warning:
Be careful when using the name
property 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.
Source code such as:
function Foo() {}
const foo = new Foo();
if (foo.constructor.name === "Foo") {
console.log("'foo' is an instance of 'Foo'");
} else {
console.log("Oops!");
}
may be compressed to:
function a() {}
const b = new a();
if (b.constructor.name === "Foo") {
console.log("'foo' is an instance of 'Foo'");
} else {
console.log("Oops!");
}
In the uncompressed version, the program runs into the truthy branch and logs "'foo' is an instance of 'Foo'" — whereas, in the compressed version it behaves differently, and runs into the else branch. If you rely on the name
property, 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.
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-function-instances-name |


Intl.DateTimeFormat.prototype.format()

Intl.DateTimeFormat.prototype.format()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2017.
The format()
method of Intl.DateTimeFormat
instances formats a date according to the locale and formatting options of this Intl.DateTimeFormat
object.
Try it
const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
const date = new Date(2012, 5);
const dateTimeFormat1 = new Intl.DateTimeFormat("sr-RS", options);
console.log(dateTimeFormat1.format(date));
// Expected output: "петак, 1. јун 2012."
const dateTimeFormat2 = new Intl.DateTimeFormat("en-GB", options);
console.log(dateTimeFormat2.format(date));
// Expected output: "Friday, 1 June 2012"
const dateTimeFormat3 = new Intl.DateTimeFormat("en-US", options);
console.log(dateTimeFormat3.format(date));
// Expected output: "Friday, June 1, 2012"
Syntax
format(date)
Parameters
date
-
The date to format. Can be a
Date
orTemporal.PlainDateTime
object. Additionally can be aTemporal.PlainTime
,Temporal.PlainDate
,Temporal.PlainYearMonth
, orTemporal.PlainMonthDay
object if theDateTimeFormat
object was configured to print at least one relevant part of the date.Note: A
Temporal.ZonedDateTime
object will always throw aTypeError
; useTemporal.ZonedDateTime.prototype.toLocaleString()
or convert it to aTemporal.PlainDateTime
object instead.Omitting it results in formatting the current date (as returned by
Date.now()
), which could be slightly confusing, so it is advisable to always explicitly pass a date.
Return value
A string representing the given date
formatted according to the locale and formatting options of this Intl.DateTimeFormat
object.
Note:
Most of the time, the formatting returned by format()
is consistent. However, the output may vary between implementations, even within the same locale — 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()
to hardcoded constants.
Examples
Using format
Use the format
getter function for formatting a single date, here for
Serbia:
const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
const dateTimeFormat = new Intl.DateTimeFormat("sr-RS", options);
console.log(dateTimeFormat.format(new Date()));
// "недеља, 7. април 2013."
Using format with map
Use the format
getter function for formatting all dates in an array. Note
that the function is bound to the Intl.DateTimeFormat
from which it was obtained, so it can be passed directly to
Array.prototype.map()
.
const a = [new Date(2012, 8), new Date(2012, 11), new Date(2012, 3)];
const options = { year: "numeric", month: "long" };
const dateTimeFormat = new Intl.DateTimeFormat("pt-BR", options);
const formatted = a.map(dateTimeFormat.format);
console.log(formatted.join("; "));
// "setembro de 2012; dezembro de 2012; abril de 2012"
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # sec-intl.datetimeformat.prototype.format |


TypeError: matchAll/replaceAll must be called with a global RegExp
The JavaScript exception "TypeError: matchAll/replaceAll must be called with a global RegExp" occurs when the String.prototype.matchAll()
or String.prototype.replaceAll()
method is used with a RegExp
object that does not have the global
flag set.
Message
TypeError: 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)
Error type
TypeError
What went wrong?
The String.prototype.matchAll()
and String.prototype.replaceAll()
methods require a RegExp
object with the global
flag 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
flag is redundant when using these methods (because these methods always do a global replacement), they are still required to make the intention clear.
It's worth noting that the g
flag validation is done in the matchAll
and replaceAll
methods. If you use the [Symbol.matchAll]()
method of RegExp
instead, you won't get this error, but there will only be a single match.
Examples
Invalid cases
"abc".matchAll(/./); // TypeError
"abc".replaceAll(/./, "f"); // TypeError
Valid cases
If you intend to do global matching/replacement: either add the g
flag, or construct a new RegExp
object with the g
flag, if you want to keep the original regex unchanged.
[..."abc".matchAll(/./g)]; // [[ "a" ], [ "b" ], [ "c" ]]
"abc".replaceAll(/./g, "f"); // "fff"
const existingPattern = /./;
const newPattern = new RegExp(
existingPattern.source,
`${existingPattern.flags}g`,
);
"abc".replaceAll(newPattern, "f"); // "fff"
If you only intend to do a single matching/replacement: use String.prototype.match()
or String.prototype.replace()
instead. You can also use the [Symbol.matchAll]()
method if you want an iterator like matchAll
returns that only contains one match, but doing so will be very confusing.
"abc".match(/./); // [ "a" ]
"abc".replace(/./, "f"); // "fbc"
[..././[Symbol.matchAll]("abc")]; // [[ "a" ]]


Number.MIN_VALUE

Number.MIN_VALUE
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The Number.MIN_VALUE
static data property represents the smallest positive numeric value representable in JavaScript.
Try it
function divide(x, y) {
if (x / y < Number.MIN_VALUE) {
return "Process as 0";
}
return x / y;
}
console.log(divide(5e-324, 1));
// Expected output: 5e-324
console.log(divide(5e-324, 2));
// Expected output: "Process as 0"
Value
2-1074, or 5E-324
.
Property attributes of Number.MIN_VALUE | |
|---|---|
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
Number.MIN_VALUE
is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support — 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
may be larger.
In 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
.
Because MIN_VALUE
is a static property of Number
, you always use it as Number.MIN_VALUE
, rather than as a property of a number value.
Examples
Using MIN_VALUE
The following code divides two numeric values. If the result is greater than or equal to MIN_VALUE
, the func1
function is called; otherwise, the func2
function is called.
if (num1 / num2 >= Number.MIN_VALUE) {
func1();
} else {
func2();
}
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-number.min_value |


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


Temporal.Duration.prototype.nanoseconds

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


Intl.NumberFormat.supportedLocalesOf()

Intl.NumberFormat.supportedLocalesOf()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2017.
The Intl.NumberFormat.supportedLocalesOf()
static 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.
Try it
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.NumberFormat.supportedLocalesOf(locales, options));
// Expected output: Array ["id-u-co-pinyin", "de-ID"]
// (Note: the exact output may be browser-dependent)
Syntax
Intl.NumberFormat.supportedLocalesOf(locales)
Intl.NumberFormat.supportedLocalesOf(locales, options)
Parameters
locales
-
A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the
locales
argument, see the parameter description on theIntl
main page. options
Optional-
An object that may have the following property:
localeMatcher
-
The locale matching algorithm to use. Possible values are
"lookup"
and"best fit"
; the default is"best fit"
. For information about this option, see the Intl page.
Return value
An 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.
Examples
Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in number formatting, supportedLocalesOf
returns the Indonesian and German language tags unchanged, even though pinyin
collation 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"
algorithm here — a "best fit"
matcher 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.
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.NumberFormat.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # sec-intl.numberformat.supportedlocalesof |


Intl.NumberFormat.prototype.resolvedOptions()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2017.
The resolvedOptions()
method of Intl.NumberFormat
instances returns a new object with properties reflecting the options computed during initialization of this NumberFormat
object.
Try it
const numberFormat = new Intl.NumberFormat("de-DE");
const options = numberFormat.resolvedOptions();
console.log(options.locale);
// Expected output: "de-DE"
console.log(options.numberingSystem);
// Expected output: "latn"
console.log(options.style);
// Expected output: "decimal"
Syntax
resolvedOptions()
Parameters
None.
Return value
A new object with properties reflecting the options computed during the initialization of this NumberFormat
object. The object has the following properties, in the order they are listed:
locale
-
The BCP 47 language tag for the locale actually used, determined by the locale negotiation process. Only the
nu
Unicode extension key, if requested, may be included in the output. numberingSystem
-
The value provided for this property in the
options
argument, or using the Unicode extension key"nu"
, with default filled in as needed. It is a supported numbering system for this locale. The default is locale dependent. style
-
The value provided for this property in the
options
argument, with default filled in as needed. It is either"decimal"
,"percent"
,"currency"
, or"unit"
. The default is"decimal"
. currency
Optional-
The value provided for this property in the
options
argument. It is only present ifstyle
is"currency"
. It is an ISO 4217 currency code; seeIntl.supportedValuesOf()
. It is required ifstyle
is"currency"
so there is no default. currencyDisplay
Optional-
The value provided for this property in the
options
argument, with default filled in as needed. It is only present ifstyle
is"currency"
. It is either"code"
,"symbol"
,"narrowSymbol"
, or"name"
. The default is"symbol"
. currencySign
Optional-
The value provided for this property in the
options
argument, with default filled in as needed. It is only present ifstyle
is"currency"
. It is either"standard"
or"accounting"
. The default is"standard"
. unit
Optional-
The value provided for this property in the
options
argument. It is only present ifstyle
is"unit"
. It is a sanctioned unit identifier from the full CLDR list. It is required ifstyle
is"unit"
so there is no default. unitDisplay
Optional-
The value provided for this property in the
options
argument, with default filled in as needed. It is only present ifstyle
is"unit"
. It is either"short"
,"narrow"
, or"long"
. The default is"short"
. minimumIntegerDigits
-
The value provided for this property in the
options
argument, with default filled in as needed. It is an integer between1
and21
. The default is1
. minimumFractionDigits
,maximumFractionDigits
Optional-
The value provided for these properties in the
options
argument, with defaults filled in as needed. They are only present if necessary; see digit options. It is an integer between0
and100
. minimumSignificantDigits
,maximumSignificantDigits
Optional-
The value provided for these properties in the
options
argument, with defaults filled in as needed. They are only present if necessary; see digit options. It is an integer between1
and21
. useGrouping
-
The value provided for this property in the
options
argument, with default filled in as needed, and with some values normalized. It is either"always"
,"auto"
,"min2"
, or the booleanfalse
. The default is"min2"
ifnotation
is"compact"
, and"auto"
otherwise. notation
-
The value provided for this property in the
options
argument, with default filled in as needed. It is either"standard"
,"scientific"
,"engineering"
, or"compact"
. The default is"standard"
. compactDisplay
Optional-
The value provided for this property in the
options
argument, with default filled in as needed. It is only present ifnotation
is"compact"
. It is either"short"
or"long"
. The default is"short"
. signDisplay
-
The value provided for this property in the
options
argument, with default filled in as needed. It is either"auto"
,"always"
,"exceptZero"
,"negative"
, or"never"
. The default is"auto"
. roundingIncrement
-
The value provided for this property in the
options
argument, with default filled in as needed. It is one of1
,2
,5
,10
,20
,25
,50
,100
,200
,250
,500
,1000
,2000
,2500
, and5000
. The default is1
. roundingMode
-
The value provided for this property in the
options
argument, with default filled in as needed. It is one of"ceil"
,"floor"
,"expand"
,"trunc"
,"halfCeil"
,"halfFloor"
,"halfExpand"
,"halfTrunc"
, and"halfEven"
. The default is"halfExpand"
. roundingPriority
-
The value provided for this property in the
options
argument, with default filled in as needed. It is either"auto"
,"morePrecision"
, or"lessPrecision"
. The default is"auto"
. trailingZeroDisplay
-
The value provided for this property in the
options
argument, with default filled in as needed. It is either"auto"
or"stripIfInteger"
. The default is"auto"
.
Examples
Using the resolvedOptions
method
// Create a NumberFormat
const de = new Intl.NumberFormat("de-DE", {
style: "currency",
currency: "USD",
maximumFractionDigits: 2,
roundingIncrement: 5,
roundingMode: "halfCeil",
});
// Resolve the options
const usedOptions = de.resolvedOptions();
console.log(usedOptions.locale); // "de-DE"
console.log(usedOptions.numberingSystem); // "latn"
console.log(usedOptions.compactDisplay); // undefined ("notation" not set to "compact")
console.log(usedOptions.currency); // "USD"
console.log(usedOptions.currencyDisplay); // "symbol"
console.log(usedOptions.currencySign); // "standard"
console.log(usedOptions.minimumIntegerDigits); // 1
console.log(usedOptions.minimumFractionDigits); // 2
console.log(usedOptions.maximumFractionDigits); // 2
console.log(usedOptions.minimumSignificantDigits); // undefined (maximumFractionDigits is set)
console.log(usedOptions.maximumSignificantDigits); // undefined (maximumFractionDigits is set)
console.log(usedOptions.notation); // "standard"
console.log(usedOptions.roundingIncrement); // 5
console.log(usedOptions.roundingMode); // halfCeil
console.log(usedOptions.roundingPriority); // auto
console.log(usedOptions.signDisplay); // "auto"
console.log(usedOptions.style); // "currency"
console.log(usedOptions.trailingZeroDisplay); // auto
console.log(usedOptions.useGrouping); // auto
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # sec-intl.numberformat.prototype.resolvedoptions |


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


Right shift (>>)

Right shift (>>)
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The right shift (>>
) 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.
Try it
const a = 5; // 00000000000000000000000000000101
const b = 2; // 00000000000000000000000000000010
const c = -5; // 11111111111111111111111111111011
console.log(a >> b); // 00000000000000000000000000000001
// Expected output: 1
console.log(c >> b); // 11111111111111111111111111111110
// Expected output: -2
Syntax
x >> y
Description
The >>
operator 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
is thrown if one operand becomes a BigInt but the other becomes a number.
Since 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".
The 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
and -9
:
9 (base 10): 00000000000000000000000000001001 (base 2) -9 (base 10): 11111111111111111111111111110111 (base 2)
The binary representation under two's complement of the negative decimal (base 10) number -9
is formed by inverting all the bits of its opposite number, which is 9
and 00000000000000000000000000001001
in binary, and adding 1
.
In both cases, the sign of the binary number is given by its leftmost bit: for the positive decimal number 9
, the leftmost bit of the binary representation is 0
, and for the negative decimal number -9
, the leftmost bit of the binary representation is 1
.
Given those binary representations of the decimal (base 10) numbers 9
, and -9
:
9 >> 2
yields 2:
9 (base 10): 00000000000000000000000000001001 (base 2) -------------------------------- 9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
Notice how two rightmost bits, 01
, have been shifted off, and two copies of the leftmost bit, 0
have been shifted in from the left.
-9 >> 2
yields -3
:
-9 (base 10): 11111111111111111111111111110111 (base 2) -------------------------------- -9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
Notice how two rightmost bits, 11
, have been shifted off. But as far as the leftmost bits: in this case, the leftmost bit is 1
. So two copies of that leftmost 1
bit have been shifted in from the left — which preserves the negative sign.
The binary representation 11111111111111111111111111111101
is equal to the negative decimal (base 10) number -3
, 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
, which is 00000000000000000000000000000011
, and then adding one.
If 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:
Before: 11100110111110100000000000000110000000000001 After: 10100000000000000110000000000001
The 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
is the same as 100 >> 0
(and produces 100
) because 32 modulo 32 is 0.
Warning:
You may see people using >> 0
to truncate numbers to integers. Right shifting any number x
by 0
returns x
converted to a 32-bit integer, which additionally removes leading bits for numbers outside the range -2147483648 to 2147483647. Use Math.trunc()
instead.
For BigInts, there's no truncation. Conceptually, understand positive BigInts as having an infinite number of leading 0
bits, and negative BigInts having an infinite number of leading 1
bits.
Examples
Using right shift
9 >> 2; // 2
-9 >> 2; // -3
9n >> 2n; // 2n
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-signed-right-shift-operator |


Date.prototype.toTemporalInstant()

Date.prototype.toTemporalInstant()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
The toTemporalInstant()
method of Date
instances returns a new Temporal.Instant
object with the same epochMilliseconds
value as this date's timestamp.
Use this method to convert legacy Date
values to the Temporal
API, then further convert it to other Temporal
classes as necessary.
Syntax
js
toTemporalInstant()
Parameters
None.
Return value
A new Temporal.Instant
object with the same epochMilliseconds
value as this date's timestamp. Its microsecond and nanosecond components are always 0
.
Exceptions
RangeError
-
Thrown if the date is invalid (it has a timestamp of
NaN
).
Examples
Using toTemporalInstant()
js
const legacyDate = new Date("2021-07-01T12:34:56.789Z");
const instant = legacyDate.toTemporalInstant();
// Further convert it to other objects
const zdt = instant.toZonedDateTimeISO("UTC");
const date = zdt.toPlainDate();
console.log(date.toString()); // 2021-07-01
Specifications
| Specification |
|---|
| Temporal # sec-date.prototype.totemporalinstant |


Intl.Collator() constructor

Intl.Collator() constructor
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2017.
The Intl.Collator()
constructor creates Intl.Collator
objects.
Try it
console.log(["Z", "a", "z", "ä"].sort(new Intl.Collator("de").compare));
// Expected output: Array ["a", "ä", "z", "Z"]
console.log(["Z", "a", "z", "ä"].sort(new Intl.Collator("sv").compare));
// Expected output: Array ["a", "z", "Z", "ä"]
console.log(
["Z", "a", "z", "ä"].sort(
new Intl.Collator("de", { caseFirst: "upper" }).compare,
),
);
// Expected output: Array ["a", "ä", "Z", "z"]
Syntax
new Intl.Collator()
new Intl.Collator(locales)
new Intl.Collator(locales, options)
Intl.Collator()
Intl.Collator(locales)
Intl.Collator(locales, options)
Note:
Intl.Collator()
can be called with or without new
. Both create a new Intl.Collator
instance.
Parameters
locales
Optional-
A string with a BCP 47 language tag or an
Intl.Locale
instance, or an array of such locale identifiers. The runtime's default locale is used whenundefined
is passed or when none of the specified locale identifiers is supported. For the general form and interpretation of thelocales
argument, see the parameter description on theIntl
main page.The following Unicode extension keys are allowed:
These keys can also be set with
options
(as listed below). When both are set, theoptions
property takes precedence. options
Optional-
An object containing the following properties, in the order they are retrieved (all of them are optional):
usage
-
Whether 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:
"sort"
(default)-
For sorting a list of strings.
"search"
-
For filtering a list of strings by testing each list item for a full-string match against a key. With
"search"
, the caller should only pay attention to whethercompare()
returns zero or non-zero and should not distinguish the non-zero return values from each other. That is, it is inappropriate to use"search"
for sorting/ordering.
localeMatcher
-
The locale matching algorithm to use. Possible values are
"lookup"
and"best fit"
; the default is"best fit"
. For information about this option, see Locale identification and negotiation. collation
-
Variant collations for certain locales, such as
"emoji"
,"pinyin"
,"stroke"
, and so on. Only has an effect whenusage
is"sort"
(because"search"
is underlyingly its own collation type). For a list of supported collation types, seeIntl.supportedValuesOf()
; the default is"default"
. This option can also be set through theco
Unicode extension key; if both are provided, thisoptions
property takes precedence. numeric
-
Whether numeric collation should be used, such that "1" < "2" < "10". Possible values are
true
andfalse
; the default isfalse
. This option can also be set through thekn
Unicode extension key; if both are provided, thisoptions
property takes precedence. caseFirst
-
Whether upper case or lower case should sort first. Possible values are
"upper"
,"lower"
, and"false"
(use the locale's default); the default is"false"
. This option can also be set through thekf
Unicode extension key; if both are provided, thisoptions
property takes precedence. sensitivity
-
Which differences in the strings should lead to non-zero result values. Possible values are:
"base"
-
Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A. In the Unicode collation algorithm, this is equivalent to the primary strength level.
"accent"
-
Only strings that differ in base letters or accents and other diacritic marks compare as unequal. Examples: a ≠ b, a ≠ á, a = A. In the Unicode collation algorithm, this is equivalent to the secondary strength level.
"case"
-
Only strings that differ in base letters or case compare as unequal. Examples: a ≠ b, a = á, a ≠ A. In the Unicode collation algorithm, this is equivalent to the primary strength level with case level handling.
"variant"
-
Strings 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 ≠ b, a ≠ á, a ≠ A. In the Unicode collation algorithm, this is equivalent to the tertiary strength level.
The default is
"variant"
for usage"sort"
; it's locale dependent for usage"search"
per spec, but is usually also"variant"
. Because the core functionality of"search"
is accent-insensitive and case-insensitive filtering, setting it to"base"
makes the most sense (and perhaps"case"
). ignorePunctuation
-
Whether punctuation should be ignored. Possible values are
true
andfalse
. The default istrue
for Thai (th
) andfalse
for all other languages.
Exceptions
RangeError
-
Thrown if
locales
oroptions
contain invalid values.
Examples
Using Collator
The following example demonstrates the different potential results for a string occurring before, after, or at the same level as another:
console.log(new Intl.Collator().compare("a", "c")); // -1, or some other negative value
console.log(new Intl.Collator().compare("c", "a")); // 1, or some other positive value
console.log(new Intl.Collator().compare("a", "a")); // 0
Note 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.
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # sec-intl-collator-constructor |


Temporal.Now.plainDateTimeISO()

Temporal.Now.plainDateTimeISO()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
The Temporal.Now.plainDateTimeISO()
static method returns the current date and time as a Temporal.PlainDateTime
object, in the ISO 8601 calendar and the specified time zone.
Syntax
Temporal.Now.plainDateTimeISO()
Temporal.Now.plainDateTimeISO(timeZone)
Parameters
timeZone
Optional-
Either a string or a
Temporal.ZonedDateTime
instance representing the time zone to interpret the system time in. If aTemporal.ZonedDateTime
instance, its time zone is used. If a string, it can be a named time zone identifier, an offset time zone identifier, or a date-time string containing a time zone identifier or an offset (see time zones and offsets for more information).
Return value
The current date and time in the specified time zone, as a Temporal.PlainDateTime
object using the ISO 8601 calendar. Has the same precision as Temporal.Now.instant()
.
Exceptions
RangeError
-
Thrown if the time zone is invalid.
Examples
Using Temporal.Now.plainDateTimeISO()
// The current date and time in the system's time zone
const dateTime = Temporal.Now.plainDateTimeISO();
console.log(dateTime); // e.g.: 2021-10-01T06:12:34.567890123
// The current date and time in the "America/New_York" time zone
const dateTimeInNewYork = Temporal.Now.plainDateTimeISO("America/New_York");
console.log(dateTimeInNewYork); // e.g.: 2021-09-30T23:12:34.567890123
Specifications
| Specification |
|---|
| Temporal # sec-temporal.now.plaindatetimeiso |


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

# Original Wiki contributors
buckcronk
sydh5524
mfuji09
pgmreddy
wbamberg
fscholz
Brettz9
tjcrowder
Robg1
fanerge
aetonsi
irenesmith
james-owen
rwaldron
PeterDavidCarter
Sheppy
roanongh
jameshkramer
arai
MichaelRushton
Mingun
teoli
ethertank
ziyunfei
jstrimpel
evilpie
Mgjbot
Maian
Nickolay
Dria


Lexical grammar

Lexical grammar
This page describes JavaScript's lexical grammar. JavaScript source text is just a sequence of characters — 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 — 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.
Format-control characters
Format-control characters have no visual representation but are used to control the interpretation of the text.
| Code point | Name | Abbreviation | Description |
|---|---|---|---|
| U+200C | Zero width non-joiner | <ZWNJ> | Placed between characters to prevent being connected into ligatures in certain languages (Wikipedia). |
| U+200D | Zero width joiner | <ZWJ> | 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). |
| U+FEFF | Byte order mark | <BOM> | 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). |
In JavaScript source text, <ZWNJ> and <ZWJ> are treated as identifier parts, while <BOM> (also called a zero-width no-break space <ZWNBSP> when not at the start of text) is treated as white space.
White space
White 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.
| Code point | Name | Abbreviation | Description | Escape sequence |
|---|---|---|---|---|
| U+0009 | Character tabulation | <TAB> | Horizontal tabulation | \t |
| U+000B | Line tabulation | <VT> | Vertical tabulation | \v |
| U+000C | Form feed | <FF> | Page breaking control character (Wikipedia). | \f |
| U+0020 | Space | <SP> | Normal space | |
| U+00A0 | No-break space | <NBSP> | Normal space, but no point at which a line may break | |
| U+FEFF | Zero-width no-break space | <ZWNBSP> | When not at the start of a script, the BOM marker is a normal whitespace character. | |
| Others | Other Unicode space characters | <USP> | Characters in the "Space_Separator" general category |
Note: 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.
Note:
Changes 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
changed from 0
to 1
.
Line terminators
In 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.
Outside the context of lexical grammar, white space and line terminators are often conflated. For example, String.prototype.trim()
removes all white space and line terminators from the beginning and end of a string. The \s
character class escape in regular expressions matches all white space and line terminators.
Only 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).
Comments
Comments 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.
JavaScript has two long-standing ways to add comments to code: line comments and block comments. In addition, there's a special hashbang comment syntax.
Line comments
The first way is the //
comment; this makes all text following it on the same line into a comment. For example:
function comment() {
// This is a one line JavaScript comment
console.log("Hello world!");
}
comment();
Block comments
The second way is the /* */
style, which is much more flexible.
For example, you can use it on a single line:
function comment() {
/* This is a one line JavaScript comment */
console.log("Hello world!");
}
comment();
You can also make multiple-line comments, like this:
function comment() {
/* This comment spans multiple lines. Notice
that we don't need to end the comment until we're done. */
console.log("Hello world!");
}
comment();
You 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:
function comment(x) {
console.log("Hello " + x /* insert the value of x */ + " !");
}
comment("world");
In addition, you can use it to disable code to prevent it from running, by wrapping code in a comment, like this:
function comment() {
/* console.log("Hello world!"); */
}
comment();
In this case, the console.log()
call is never issued, since it's inside a comment. Any number of lines of code can be disabled this way.
Block comments that contain at least one line terminator behave like line terminators in automatic semicolon insertion.
Hashbang comments
There's a special third comment syntax, the hashbang comment. A hashbang comment behaves exactly like a single line-only (//
) comment, except that it begins with #!
and is only valid at the absolute start of a script or module. Note also that no whitespace of any kind is permitted before the #!
. The comment consists of all the characters after #!
up to the end of the first line; only one such comment is permitted.
Hashbang 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:
#!/usr/bin/env node
console.log("Hello world");
The JavaScript interpreter will treat it as a normal comment — it only has semantic meaning to the shell if the script is directly run in a shell.
Warning: 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 — because it's stripped during UTF-8 decoding, before the source text is analyzed — a Unix/Linux shell will not recognize the hashbang if it's preceded by a BOM character.
You must only use the #!
comment style to specify a JavaScript interpreter. In all other cases just use a //
comment (or multiline comment).
Identifiers
An identifier is used to link a value with a name. Identifiers can be used in various places:
const decl = 1; // Variable declaration (may also be `let` or `var`)
function fn() {} // Function declaration
const obj = { key: "value" }; // Object keys
// Class declaration
class C {
#priv = "value"; // Private field
}
lbl: console.log(1); // Label
In JavaScript, identifiers are commonly made of alphanumeric characters, underscores (_
), and dollar signs ($
). Identifiers are not allowed to start with numbers. However, JavaScript identifiers are not only limited to ASCII — many Unicode code points are allowed as well. Namely:
- Start characters can be any character in the ID_Start category plus
_
and$
. - After the first character, you can use any character in the ID_Continue category plus U+200C (ZWNJ) and U+200D (ZWJ).
Note:
If, for some reason, you need to parse some JavaScript source yourself, do not assume all identifiers follow the pattern /[A-Za-z_$][\w$]*/
(i.e., ASCII-only)! The range of identifiers can be described by the regex /[$_\p{ID_Start}][$\p{ID_Continue}]*/u
(excluding unicode escape sequences).
In addition, JavaScript allows using Unicode escape sequences in the form of \u0000
or \u{000000}
in identifiers, which encode the same string value as the actual Unicode characters. For example, 你好
and \u4f60\u597d
are the same identifiers:
const 你好 = "Hello";
console.log(\u4f60\u597d); // Hello
Not 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.
function import() {} // Illegal: import is a reserved word.
Most notably, private elements and object properties allow reserved words.
const obj = { import: "value" }; // Legal despite `import` being reserved
class C {
#import = "value";
}
Keywords
Keywords are tokens that look like identifiers but have special meanings in JavaScript. For example, the keyword async
before a function declaration indicates that the function is asynchronous.
Some 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 — for example, async
can be used as an identifier anywhere. Some keywords are only contextually reserved — for example, await
is only reserved within the body of an async function, and let
is only reserved in strict mode code, or const
and let
declarations.
Identifiers are always compared by string value, so escape sequences are interpreted. For example, this is still a syntax error:
const els\u{65} = 1;
// `els\u{65}` encodes the same identifier as `else`
Reserved words
These keywords cannot be used as identifiers for variables, functions, classes, etc. anywhere in JavaScript source.
break
case
catch
class
const
continue
debugger
default
delete
do
else
export
extends
false
finally
for
function
if
import
in
instanceof
new
null
return
super
switch
this
throw
true
try
typeof
var
void
while
with
The following are only reserved when they are found in strict mode code:
let
(also reserved inconst
,let
, and class declarations)static
yield
(also reserved in generator function bodies)
The following are only reserved when they are found in module code or async function bodies:
Future reserved words
The 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.
These are always reserved:
enum
The following are only reserved when they are found in strict mode code:
implements
interface
package
private
protected
public
Future reserved words in older standards
The following are reserved as future keywords by older ECMAScript specifications (ECMAScript 1 till 3).
abstract
boolean
byte
char
double
final
float
goto
int
long
native
short
synchronized
throws
transient
volatile
Identifiers with special meanings
A few identifiers have a special meaning in some contexts without being reserved words of any kind. They include:
arguments
(not a keyword, but cannot be declared as identifier in strict mode)as
(import * as ns from "mod"
)async
eval
(not a keyword, but cannot be declared as identifier in strict mode)from
(import x from "mod"
)get
of
set
Literals
Note: This section discusses literals that are atomic tokens. Object literals and array literals are expressions that consist of a series of tokens.
Null literal
See also null
for more information.
null
Boolean literal
See also boolean type for more information.
true
false
Numeric literals
The Number and BigInt types use numeric literals.
Decimal
1234567890
42
Decimal literals can start with a zero (0
) followed by another decimal digit, but if all digits after the leading 0
are smaller than 8, the number is interpreted as an octal number. This is considered a legacy syntax, and number literals prefixed with 0
, whether interpreted as octal or decimal, cause a syntax error in strict mode — so, use the 0o
prefix instead.
0888 // 888 parsed as decimal
0777 // parsed as octal, 511 in decimal
Exponential
The decimal exponential literal is specified by the following format: beN
; where b
is a base number (integer or floating), followed by an E
or e
character (which serves as separator or exponent indicator) and N
, which is exponent or power number – a signed integer.
0e-5 // 0
0e+5 // 0
5e1 // 50
175e-2 // 1.75
1e3 // 1000
1e-3 // 0.001
1E3 // 1000
Binary
Binary number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "B" (0b
or 0B
). Any character after the 0b
that is not 0 or 1 will terminate the literal sequence.
0b10000000000000000000000000000000 // 2147483648
0b01111111100000000000000000000000 // 2139095040
0B00000000011111111111111111111111 // 8388607
Octal
Octal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "O" (0o
or 0O)
. Any character after the 0o
that is outside the range (01234567) will terminate the literal sequence.
0O755 // 493
0o644 // 420
Hexadecimal
Hexadecimal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "X" (0x
or 0X
). Any character after the 0x
that is outside the range (0123456789ABCDEF) will terminate the literal sequence.
0xFFFFFFFFFFFFF // 4503599627370495
0xabcdef123456 // 188900967593046
0XA // 10
BigInt literal
The BigInt type is a numeric primitive in JavaScript that can represent integers with arbitrary precision. BigInt literals are created by appending n
to the end of an integer.
123456789123456789n // 123456789123456789
0o777777777777n // 68719476735
0x123456789ABCDEFn // 81985529216486895
0b11101001010101010101n // 955733
BigInt literals cannot start with 0
to avoid confusion with legacy octal literals.
0755n; // SyntaxError: invalid BigInt syntax
For octal BigInt
numbers, always use zero followed by the letter "o" (uppercase or lowercase):
0o755n;
For more information about BigInt
, see also JavaScript data structures.
Numeric separators
To improve readability for numeric literals, underscores (_
, U+005F
) can be used as separators:
1_000_000_000_000
1_050.95
0b1010_0001_1000_0101
0o2_2_5_6
0xA0_B0_C0
1_000_000_000_000_000_000_000n
Note these limitations:
// More than one underscore in a row is not allowed
100__000; // SyntaxError
// Not allowed at the end of numeric literals
100_; // SyntaxError
// Can not be used after leading 0
0_1; // SyntaxError
String literals
A 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:
- U+005C \ (backslash)
- U+000D <CR>
- U+000A <LF>
- The same kind of quote that begins the string literal
Any 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.
'foo'
"bar"
The following subsections describe various escape sequences (\
followed 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
is the same as z
. 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 — see Character escape.
Escape sequences
Special characters can be encoded using escape sequences:
| Escape sequence | Unicode code point |
|---|---|
\0 |
null character (U+0000 NULL) |
\' |
single quote (U+0027 APOSTROPHE) |
\" |
double quote (U+0022 QUOTATION MARK) |
\\ |
backslash (U+005C REVERSE SOLIDUS) |
\n |
newline (U+000A LINE FEED; LF) |
\r |
carriage return (U+000D CARRIAGE RETURN; CR) |
\v |
vertical tab (U+000B LINE TABULATION) |
\t |
tab (U+0009 CHARACTER TABULATION) |
\b |
backspace (U+0008 BACKSPACE) |
\f |
form feed (U+000C FORM FEED) |
\ followed by a line terminator |
empty string |
The last escape sequence, \
followed by a line terminator, is useful for splitting a string literal across multiple lines without changing its meaning.
const longString =
"This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable.";
Make 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.
You can also use the +
operator to append multiple strings together, like this:
const longString =
"This is a very long string which needs " +
"to wrap across multiple lines because " +
"otherwise my code is unreadable.";
Both of the above methods result in identical strings.
Hexadecimal escape sequences
Hexadecimal escape sequences consist of \x
followed by exactly two hexadecimal digits representing a code unit or code point in the range 0x0000 to 0x00FF.
"\xA9"; // "©"
Unicode escape sequences
A Unicode escape sequence consists of exactly four hexadecimal digits following \u
. 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.
See also String.fromCharCode()
and String.prototype.charCodeAt()
.
"\u00A9"; // "©" (U+A9)
Unicode code point escapes
A Unicode code point escape consists of \u{
, followed by a code point in hexadecimal base, followed by }
. 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.
See also String.fromCodePoint()
and String.prototype.codePointAt()
.
"\u{2F804}"; // CJK COMPATIBILITY IDEOGRAPH-2F804 (U+2F804)
// the same character represented as a surrogate pair
"\uD87E\uDC04";
Regular expression literals
Regular expression literals are enclosed by two forward slashes (/
). 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 ([]
). Some characters (namely, those that are identifier parts) can appear after the closing slash, denoting flags.
The lexical grammar is very lenient: not all regular expression literals that get identified as one token are valid regular expressions.
See also RegExp
for more information.
/ab+c/g;
/[/]/;
A regular expression literal cannot start with two forward slashes (//
), because that would be a line comment. To specify an empty regular expression, use /(?:)/
.
Template literals
One template literal consists of several tokens: `xxx${
(template head), }xxx${
(template middle), and }xxx`
(template tail) are individual tokens, while any expression may come between them.
See also template literals for more information.
`string text`;
`string text line 1
string text line 2`;
`string text ${expression} string text`;
tag`string text ${expression} string text`;
Automatic semicolon insertion
Some JavaScript statements' syntax definitions require semicolons (;
) at the end. They include:
var
,let
,const
,using
,await using
- Expression statements
do...while
continue
,break
,return
,throw
debugger
- Class field declarations (public or private)
import
,export
However, 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:
1. 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.
{ 1
2 } 3
// is transformed by ASI into:
{ 1
;2 ;} 3;
// Which is valid grammar encoding three statements,
// each consisting of a number literal
The ending ")" of do...while
is taken care of as a special case by this rule as well.
do {
// …
} while (condition) /* ; */ // ASI here
const a = 1
However, semicolons are not inserted if the semicolon would then become the separator in the for
statement's head.
for (
let a = 1 // No ASI here
a < 10 // No ASI here
a++
) {}
Semicolons 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
body and the const
declaration being a separate statement. However, because automatically inserted semicolons cannot become empty statements, this causes a declaration to become the body of the if
statement, which is not valid.
if (Math.random() > 0.5)
const x = 1 // SyntaxError: Unexpected token 'const'
2. 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.
const a = 1 /* ; */ // ASI here
This rule is a complement to the previous rule, specifically for the case where there's no "offending token" but the end of input stream.
3. When the grammar forbids line terminators in some place but a line terminator is found, a semicolon is inserted. These places include:
expr <here> ++
,expr <here> --
continue <here> lbl
break <here> lbl
return <here> expr
throw <here> expr
yield <here> expr
yield <here> * expr
(param) <here> => {}
async <here> function
,async <here> prop()
,async <here> function*
,async <here> *prop()
,async <here> (param) <here> => {}
using <here> id
,await <here> using <here> id
Here ++
is not treated as a postfix operator applying to variable b
, because a line terminator occurs between b
and ++
.
a = b
++c
// is transformed by ASI into
a = b;
++c;
Here, the return
statement returns undefined
, and the a + b
becomes an unreachable statement.
return
a + b
// is transformed by ASI into
return;
a + b;
Note 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:
const a = 1
(1).toString()
const b = 1
[1, 2, 3].forEach(console.log)
Because ()
can be seen as a function call, it would usually not trigger ASI. Similarly, []
may be a member access. The code above is equivalent to:
const a = 1(1).toString();
const b = 1[1, 2, 3].forEach(console.log);
This happens to be valid syntax. 1[1, 2, 3]
is 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.
Within classes, class fields and generator methods can be a pitfall as well.
class A {
a = 1
*gen() {}
}
It is seen as:
class A {
a = 1 * gen() {}
}
And therefore will be a syntax error around {
.
There are the following rules-of-thumb for dealing with ASI, if you want to enforce semicolon-less style:
-
Write postfix
++
and--
on the same line as their operands.jsconst a = b ++ console.log(a) // ReferenceError: Invalid left-hand side expression in prefix operation
jsconst a = b++ console.log(a)
-
The expressions after
return
,throw
, oryield
should be on the same line as the keyword.jsfunction foo() { return 1 + 1 // Returns undefined; 1 + 1 is ignored }
jsfunction foo() { return 1 + 1 } function foo() { return ( 1 + 1 ) }
-
Similarly, the label identifier after
break
orcontinue
should be on the same line as the keyword.jsouterBlock: { innerBlock: { break outerBlock // SyntaxError: Illegal break statement } }
jsouterBlock: { innerBlock: { break outerBlock } }
-
The
=>
of an arrow function should be on the same line as the end of its parameters.jsconst foo = (a, b) => a + b
jsconst foo = (a, b) => a + b
-
The
async
of async functions, methods, etc. cannot be directly followed by a line terminator.jsasync function foo() {}
jsasync function foo() {}
-
The
using
keyword inusing
andawait using
statements should be on the same line as the first identifier it declares.jsusing resource = acquireResource()
jsusing resource = acquireResource()
-
If a line starts with one of
(
,[
,`
,+
,-
,/
(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 (() => { // … })() // 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)
js;(() => { // … })() ;[1, 2, 3].forEach(console.log) ;`string text ${data}`.match(pattern).forEach(console.log) ;+a.toString() ;-a.toString() ;/pattern/.exec(str).forEach(console.log)
-
Class fields should preferably always be ended with semicolons — in addition to the previous rule (which includes a field declaration followed by a computed property, since the latter starts with
[
), 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() {} }
jsclass A { a = 1; [b] = 2; *gen() {} }
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification |
Browser compatibility
See also
- Grammar and types guide
- Micro-feature from ES6, now in Firefox Aurora and Nightly: binary and octal numbers by Jeff Walden (2013)
- JavaScript character escape sequences by Mathias Bynens (2011)


Iteration protocols

Iteration protocols
Iteration protocols aren't new built-ins or syntax, but protocols. These protocols can be implemented by any object by following some conventions.
There are two protocols: The iterable protocol and the iterator protocol.
The iterable protocol
The iterable protocol allows JavaScript objects to define or customize their iteration behavior, such as what values are looped over in a for...of
construct. Some built-in types are built-in iterables with a default iteration behavior, such as Array
or Map
, while other types (such as Object
) are not.
In order to be iterable, an object must implement the [Symbol.iterator]()
method, meaning that the object (or one of the objects up its prototype chain) must have a property with a [Symbol.iterator]
key which is available via constant Symbol.iterator
:
[Symbol.iterator]()
-
A zero-argument function that returns an object, conforming to the iterator protocol.
Whenever an object needs to be iterated (such as at the beginning of a for...of
loop), its [Symbol.iterator]()
method is called with no arguments, and the returned iterator is used to obtain the values to be iterated.
Note 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
keyword can be used to access the properties of the iterable object, to decide what to provide during the iteration.
This 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
.
The iterator protocol
The 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.
An object is an iterator when it implements a next()
method with the following semantics:
next()
-
A function that accepts zero or one argument and returns an object conforming to the
IteratorResult
interface (see below). If a non-object value gets returned (such asfalse
orundefined
) when a built-in language feature (such asfor...of
) is using the iterator, aTypeError
("iterator.next() returned a non-object value"
) will be thrown.
All iterator protocol methods (next()
, return()
, and throw()
) are expected to return an object implementing the IteratorResult
interface. It must have the following properties:
done
Optional-
A boolean that's
false
if the iterator was able to produce the next value in the sequence. (This is equivalent to not specifying thedone
property altogether.)Has the value
true
if the iterator has completed its sequence. In this case,value
optionally specifies the return value of the iterator. value
Optional-
Any JavaScript value returned by the iterator. Can be omitted when
done
istrue
.
In practice, neither property is strictly required; if an object without either property is returned, it's effectively equivalent to { done: false, value: undefined }
.
If an iterator returns a result with done: true
, any subsequent calls to next()
are expected to return done: true
as well, although this is not enforced on the language level.
The next
method 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
method of generators will become the value of the corresponding yield
expression.
Optionally, the iterator can also implement the return(value)
and throw(exception)
methods, 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).
return(value)
Optional-
A function that accepts zero or one argument and returns an object conforming to the
IteratorResult
interface, typically withvalue
equal to thevalue
passed in anddone
equal totrue
. Calling this method tells the iterator that the caller does not intend to make any morenext()
calls and can perform any cleanup actions. When built-in language features callreturn()
for cleanup,value
is alwaysundefined
. throw(exception)
Optional-
A function that accepts zero or one argument and returns an object conforming to the
IteratorResult
interface, typically withdone
equal totrue
. Calling this method tells the iterator that the caller detects an error condition, andexception
is typically anError
instance. No built-in language feature callsthrow()
for cleanup purposes — it's a special feature of generators for the symmetry ofreturn
/throw
.
Note:
It is not possible to know reflectively (i.e., without actually calling next()
and validating the returned result) whether a particular object implements the iterator protocol.
It is very easy to make an iterator also iterable: just implement a [Symbol.iterator]()
method that returns this
.
// Satisfies both the Iterator Protocol and Iterable
const myIterator = {
next() {
// …
},
[Symbol.iterator]() {
return this;
},
};
Such object is called an iterable iterator. Doing so allows an iterator to be consumed by the various syntaxes expecting iterables — 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:
const generatorObject = (function* () {
yield 1;
yield 2;
yield 3;
})();
console.log(typeof generatorObject.next);
// "function" — it has a next method (which returns the right result), so it's an iterator
console.log(typeof generatorObject[Symbol.iterator]);
// "function" — it has a [Symbol.iterator] method (which returns the right iterator), so it's an iterable
console.log(generatorObject[Symbol.iterator]() === generatorObject);
// true — its [Symbol.iterator] method returns itself (an iterator), so it's an iterable iterator
All built-in iterators inherit from Iterator.prototype
, which implements the [Symbol.iterator]()
method as returning this
, so that built-in iterators are also iterable.
However, when possible, it's better for iterable[Symbol.iterator]()
to return different iterators that always start from the beginning, like Set.prototype[Symbol.iterator]()
does.
The async iterator and async iterable protocols
There 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.
An object implements the async iterable protocol when it implements the following methods:
[Symbol.asyncIterator]()
-
A zero-argument function that returns an object, conforming to the async iterator protocol.
An object implements the async iterator protocol when it implements the following methods:
next()
-
A function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the
IteratorResult
interface, and the properties have the same semantics as those of the sync iterator's. return(value)
Optional-
A function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the
IteratorResult
interface, and the properties have the same semantics as those of the sync iterator's. throw(exception)
Optional-
A function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the
IteratorResult
interface, and the properties have the same semantics as those of the sync iterator's.
Interactions between the language and iteration protocols
The language specifies APIs that either produce or consume iterables and iterators.
Built-in iterables
String
, Array
, TypedArray
, Map
, Set
, and Segments
(returned by Intl.Segmenter.prototype.segment()
) are all built-in iterables, because each of their prototype
objects implements a [Symbol.iterator]()
method. In addition, the arguments
object and some DOM collection types such as NodeList
are also iterables.
There is no object in the core JavaScript language that is async iterable. Some web APIs, such as ReadableStream
, have the Symbol.asyncIterator
method set by default.
Generator functions return generator objects, which are iterable iterators. Async generator functions return async generator objects, which are async iterable iterators.
The iterators returned from built-in iterables actually all inherit from a common class Iterator
, which implements the aforementioned [Symbol.iterator]() { return this; }
method, making them all iterable iterators. The Iterator
class also provides additional helper methods in addition to the next()
method required by the iterator protocol. You can inspect an iterator's prototype chain by logging it in a graphical console.
console.log([][Symbol.iterator]()); Array Iterator {} [[Prototype]]: Array Iterator ==> This is the prototype shared by all array iterators next: ƒ next() Symbol(Symbol.toStringTag): "Array Iterator" [[Prototype]]: Object ==> This is the prototype shared by all built-in iterators Symbol(Symbol.iterator): ƒ [Symbol.iterator]() [[Prototype]]: Object ==> This is Object.prototype
Built-in APIs accepting iterables
There are many APIs that accept iterables. Some examples include:
Map()
WeakMap()
Set()
WeakSet()
Promise.all()
Promise.allSettled()
Promise.race()
Promise.any()
Array.from()
Object.groupBy()
Map.groupBy()
const myObj = {};
new WeakSet(
(function* () {
yield {};
yield myObj;
yield {};
})(),
).has(myObj); // true
Syntaxes expecting iterables
Some statements and expressions expect iterables, for example the for...of
loops, array and parameter spreading, yield*
, and array destructuring:
for (const value of ["a", "b", "c"]) {
console.log(value);
}
// "a"
// "b"
// "c"
console.log([..."abc"]); // ["a", "b", "c"]
function* gen() {
yield* ["a", "b", "c"];
}
console.log(gen().next()); // { value: "a", done: false }
[a, b, c] = new Set(["a", "b", "c"]);
console.log(a); // "a"
When built-in syntaxes are iterating an iterator, and the last result's done
is false
(i.e., the iterator is able to produce more values) but no more values are needed, the return
method will get called if present. This can happen, for example, if a break
or return
is encountered in a for...of
loop, or if all identifiers are already bound in an array destructuring.
const obj = {
[Symbol.iterator]() {
let i = 0;
return {
next() {
i++;
console.log("Returning", i);
if (i === 3) return { done: true, value: i };
return { done: false, value: i };
},
return() {
console.log("Closing");
return { done: true };
},
};
},
};
const [a] = obj;
// Returning 1
// Closing
const [b, c, d] = obj;
// Returning 1
// Returning 2
// Returning 3
// Already reached the end (the last call returned `done: true`),
// so `return` is not called
console.log([b, c, d]); // [1, 2, undefined]; the value associated with `done: true` is not reachable
for (const b of obj) {
break;
}
// Returning 1
// Closing
The for await...of
loop and yield*
in async generator functions (but not sync generator functions) are the only ways to interact with async iterables. Using for...of
, array spreading, etc. on an async iterable that's not also a sync iterable (i.e., it has [Symbol.asyncIterator]()
but no [Symbol.iterator]()
) will throw a TypeError: x is not iterable.
Error handling
Because 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.
Non-well-formed iterables
Errors may happen when acquiring the iterator from the iterable. The language invariant enforced here is that the iterable must produce a valid iterator:
- It has a callable
[Symbol.iterator]()
method. - The
[Symbol.iterator]()
method returns an object. - The object returned by
[Symbol.iterator]()
has a callablenext()
method.
When using built-in syntax to initiate iteration on a non-well-formed iterable, a TypeError is thrown.
const nonWellFormedIterable = { [Symbol.iterator]: 1 };
[...nonWellFormedIterable]; // TypeError: nonWellFormedIterable is not iterable
nonWellFormedIterable[Symbol.iterator] = () => 1;
[...nonWellFormedIterable]; // TypeError: [Symbol.iterator]() returned a non-object value
nonWellFormedIterable[Symbol.iterator] = () => ({});
[...nonWellFormedIterable]; // TypeError: nonWellFormedIterable[Symbol.iterator]().next is not a function
For async iterables, if its [Symbol.asyncIterator]()
property has value undefined
or null
, JavaScript falls back to using the [Symbol.iterator]
property instead (and wraps the resulting iterator into an async iterator by forwarding the methods). Otherwise, the [Symbol.asyncIterator]
property must conform to the above invariants too.
This 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.
Errors during iteration
Most errors happen when stepping the iterator (calling next()
). The language invariant enforced here is that the next()
method must return an object (for async iterators, an object after awaiting). Otherwise, a TypeError is thrown.
If the invariant is broken or the next()
method 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()
method threw the error, then it has cleaned up already). If you are manually calling next()
, you may catch the error and retry calling next()
, but in general you should assume the iterator is already closed.
If 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()
method on the iterator, if one exists. This allows the iterator to perform any cleanup. The return()
method is only called for premature exits—if next()
returns done: true
, the return()
method is not called, with the assumption that the iterator has already cleaned up.
The return()
method might be invalid too! The language also enforces that the return()
method must return an object and throws a TypeError otherwise. If the return()
method throws an error, the error is propagated to the caller. However, if the return()
method is called because the caller encountered an error in its own code, then this error overrides the error thrown by the return()
method.
Usually, the caller implements error handling like this:
try {
for (const value of iterable) {
// …
}
} catch (e) {
// Handle the error
}
The catch
will be able to catch errors thrown when iterable
is not a valid iterable, when next()
throws an error, when return()
throws an error (if the for
loop exits early), and when the for
loop body throws an error.
Most iterators are implemented with generator functions, so we will demonstrate how generator functions typically handle errors:
function* gen() {
try {
yield doSomething();
yield doSomethingElse();
} finally {
cleanup();
}
}
The lack of catch
here causes errors thrown by doSomething()
or doSomethingElse()
to propagate to the caller of gen
. 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
block is necessary for generators that keep open resources. The finally
block is guaranteed to run, either when the last next()
is called or when return()
is called.
Forwarding errors
Some built-in syntaxes wrap an iterator into another iterator. They include the iterator produced by Iterator.from()
, iterator helper methods (map()
, filter()
, take()
, drop()
, and flatMap()
), yield*
, and a hidden wrapper when you use async iteration (for await...of
, Array.fromAsync
) on sync iterators. The wrapped iterator is then responsible for forwarding errors between the inner iterator and the caller.
- All wrapper iterators directly forward the
next()
method of the inner iterator, including its return value and thrown errors. - Wrapper iterators generally directly forward the
return()
method of the inner iterator. If thereturn()
method doesn't exist on the inner iterator, it returns{ done: true, value: undefined }
instead. In the case of iterator helpers: if the iterator helper'snext()
method has not been called, after trying to callreturn()
on the inner iterator, the current iterator always returns{ done: true, value: undefined }
. This is consistent with generator functions where execution hasn't entered theyield*
expression yet. yield*
is the only built-in syntax that forwards thethrow()
method of the inner iterator. For information on howyield*
forwards thereturn()
andthrow()
methods, see its own reference.
Examples
User-defined iterables
You can make your own iterables like this:
const myIterable = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
},
};
console.log([...myIterable]); // [1, 2, 3]
Basic iterator
Iterators 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.
function makeIterator(array) {
let nextIndex = 0;
return {
next() {
return nextIndex < array.length
? {
value: array[nextIndex++],
done: false,
}
: {
done: true,
};
},
};
}
const it = makeIterator(["yo", "ya"]);
console.log(it.next().value); // 'yo'
console.log(it.next().value); // 'ya'
console.log(it.next().done); // true
Infinite iterator
function idMaker() {
let index = 0;
return {
next() {
return {
value: index++,
done: false,
};
},
};
}
const it = idMaker();
console.log(it.next().value); // 0
console.log(it.next().value); // 1
console.log(it.next().value); // 2
// …
Defining an iterable with a generator
function* makeGenerator(array) {
let nextIndex = 0;
while (nextIndex < array.length) {
yield array[nextIndex++];
}
}
const gen = makeGenerator(["yo", "ya"]);
console.log(gen.next().value); // 'yo'
console.log(gen.next().value); // 'ya'
console.log(gen.next().done); // true
function* idMaker() {
let index = 0;
while (true) {
yield index++;
}
}
const it = idMaker();
console.log(it.next().value); // 0
console.log(it.next().value); // 1
console.log(it.next().value); // 2
// …
Defining an iterable with a class
State encapsulation can be done with private fields as well.
class SimpleClass {
#data;
constructor(data) {
this.#data = data;
}
[Symbol.iterator]() {
// Use a new index for each iterator. This makes multiple
// iterations over the iterable safe for non-trivial cases,
// such as use of break or nested looping over the same iterable.
let index = 0;
return {
// Note: using an arrow function allows `this` to point to the
// one of `[Symbol.iterator]()` instead of `next()`
next: () => {
if (index >= this.#data.length) {
return { done: true };
}
return { value: this.#data[index++], done: false };
},
};
}
}
const simple = new SimpleClass([1, 2, 3, 4, 5]);
for (const val of simple) {
console.log(val); // 1 2 3 4 5
}
Overriding built-in iterables
For example, a String
is a built-in iterable object:
const someString = "hi";
console.log(typeof someString[Symbol.iterator]); // "function"
String
's default iterator returns the string's code points one by one:
const iterator = someString[Symbol.iterator]();
console.log(`${iterator}`); // "[object String Iterator]"
console.log(iterator.next()); // { value: "h", done: false }
console.log(iterator.next()); // { value: "i", done: false }
console.log(iterator.next()); // { value: undefined, done: true }
You can redefine the iteration behavior by supplying our own [Symbol.iterator]()
:
// need to construct a String object explicitly to avoid auto-boxing
const someString = new String("hi");
someString[Symbol.iterator] = function () {
return {
// this is the iterator object, returning a single element (the string "bye")
next() {
return this._first
? { value: "bye", done: (this._first = false) }
: { done: true };
},
_first: true,
};
};
Notice how redefining [Symbol.iterator]()
affects the behavior of built-in constructs that use the iteration protocol:
console.log([...someString]); // ["bye"]
console.log(`${someString}`); // "hi"
Concurrent modifications when iterating
Almost 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.
Consider the following case using a URLSearchParams
:
const searchParams = new URLSearchParams(
"deleteme1=value1&key2=value2&key3=value3",
);
// Delete unwanted keys
for (const [key, value] of searchParams) {
console.log(key);
if (key.startsWith("deleteme")) {
searchParams.delete(key);
}
}
// Output:
// deleteme1
// key3
Note how it never logs key2
. This is because a URLSearchParams
is underlyingly a list of key-value pairs. When deleteme1
is visited and deleted, all other entries are shifted to the left by one, so key2
occupies the position that deleteme1
used to be in, and when the pointer moves to the next key, it lands on key3
.
Certain iterable implementations avoid this problem by setting "tombstone" values to avoid shifting the remaining values. Consider the similar code using a Map
:
const myMap = new Map([
["deleteme1", "value1"],
["key2", "value2"],
["key3", "value3"],
]);
for (const [key, value] of myMap) {
console.log(key);
if (key.startsWith("deleteme")) {
myMap.delete(key);
}
}
// Output:
// deleteme1
// key2
// key3
Note how it logs all keys. This is because Map
doesn't shift the remaining keys when one is deleted. If you want to implement something similar, here's how it may look:
const tombstone = Symbol("tombstone");
class MyIterable {
#data;
constructor(data) {
this.#data = data;
}
delete(deletedKey) {
for (let i = 0; i < this.#data.length; i++) {
if (this.#data[i][0] === deletedKey) {
this.#data[i] = tombstone;
return true;
}
}
return false;
}
*[Symbol.iterator]() {
for (const data of this.#data) {
if (data !== tombstone) {
yield data;
}
}
}
}
const myIterable = new MyIterable([
["deleteme1", "value1"],
["key2", "value2"],
["key3", "value3"],
]);
for (const [key, value] of myIterable) {
console.log(key);
if (key.startsWith("deleteme")) {
myIterable.delete(key);
}
}
Warning: 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.
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-iteration |


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


Date.prototype.valueOf()

Date.prototype.valueOf()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The valueOf()
method of Date
instances returns the number of milliseconds for this date since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.
Try it
const date1 = new Date(Date.UTC(96, 1, 2, 3, 4, 5));
console.log(date1.valueOf());
// Expected output: 823230245000
const date2 = new Date("02 Feb 1996 03:04:05 GMT");
console.log(date2.valueOf());
// Expected output: 823230245000
Syntax
valueOf()
Parameters
None.
Return value
A number representing the timestamp, in milliseconds, of this date. Returns NaN
if the date is invalid.
Description
The valueOf()
method is part of the type coercion protocol. Because Date
has a [Symbol.toPrimitive]()
method, that method always takes priority over valueOf()
when a Date
object is implicitly coerced to a number. However, Date.prototype[Symbol.toPrimitive]()
still calls this.valueOf()
internally.
The Date
object overrides the valueOf()
method of Object
. Date.prototype.valueOf()
returns the timestamp of the date, which is functionally equivalent to the Date.prototype.getTime()
method.
Examples
Using valueOf()
const d = new Date(0); // 1970-01-01T00:00:00.000Z
console.log(d.valueOf()); // 0
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-date.prototype.valueof |


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


Intl.Collator.prototype.compare()

Intl.Collator.prototype.compare()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2017.
The compare()
method of Intl.Collator
instances compares two
strings according to the sort order of this collator object.
Try it
const enCollator = new Intl.Collator("en");
const deCollator = new Intl.Collator("de");
const svCollator = new Intl.Collator("sv");
console.log(enCollator.compare("z", "a") > 0);
// Expected output: true
console.log(deCollator.compare("z", "ä") > 0);
// Expected output: true
console.log(svCollator.compare("z", "ä") > 0);
// Expected output: false
Syntax
js
compare(string1, string2)
Parameters
string1
,string2
-
The strings to compare against each other.
Return value
A number indicating how string1
and string2
compare to each other according to the sort order of this Intl.Collator
object:
- A negative value if
string1
comes beforestring2
; - A positive value if
string1
comes afterstring2
; - 0 if they are considered equal.
Examples
Using compare for array sort
Use the compare
function for sorting arrays. Note that the function
is bound to the collator from which it was obtained, so it can be passed directly to
Array.prototype.sort()
.
js
const a = ["Offenbach", "Österreich", "Odenwald"];
const collator = new Intl.Collator("de-u-co-phonebk");
a.sort(collator.compare);
console.log(a.join(", ")); // "Odenwald, Österreich, Offenbach"
Using compare for array search
Use the compare
function for finding matching strings in arrays:
js
const a = ["Congrès", "congres", "Assemblée", "poisson"];
const collator = new Intl.Collator("fr", {
usage: "search",
sensitivity: "base",
});
const s = "congres";
const matches = a.filter((v) => collator.compare(v, s) === 0);
console.log(matches.join(", ")); // "Congrès, congres"
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # sec-intl.collator.prototype.compare |