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

# Original Wiki contributors
fscholz
Bzbarsky
PatrickKettner


super

super
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2016.
The super
keyword is used to access properties on an object literal or class's [[Prototype]], or invoke a superclass's constructor.
The super.prop
and super[expr]
expressions are valid in any method definition in both classes and object literals. The super(...args)
expression is valid in class constructors.
Try it
class Foo {
constructor(name) {
this.name = name;
}
getNameSeparator() {
return "-";
}
}
class FooBar extends Foo {
constructor(name, index) {
super(name);
this.index = index;
}
// Does not get called
getNameSeparator() {
return "/";
}
getFullName() {
return this.name + super.getNameSeparator() + this.index;
}
}
const firstFooBar = new FooBar("foo", 1);
console.log(firstFooBar.name);
// Expected output: "foo"
console.log(firstFooBar.getFullName());
// Expected output: "foo-1"
Syntax
super()
super(arg1)
super(arg1, arg2)
super(arg1, arg2, /* …, */ argN)
super.propertyOnParent
super[expression]
Description
The super
keyword can be used in two ways: as a "function call" (super(...args)
), or as a "property lookup" (super.prop
and super[expr]
).
Note:
super
is a keyword and these are special syntactic constructs. super
is not a variable that points to the prototype object. Attempting to read super
itself is a SyntaxError
.
const child = {
myParent() {
console.log(super); // SyntaxError: 'super' keyword unexpected here
},
};
In the constructor body of a derived class (with extends
), the super
keyword may appear as a "function call" (super(...args)
), which must be called before the this
keyword is used, and before the constructor returns. It calls the parent class's constructor and binds the parent class's public fields, after which the derived class's constructor can further access and modify this
.
The "property lookup" form can be used to access methods and properties of an object literal's or class's [[Prototype]]. Within a class's body, the reference of super
can be either the superclass's constructor itself, or the constructor's prototype
, depending on whether the execution context is instance creation or class initialization. See the Examples section for more details.
Note that the reference of super
is determined by the class or object literal super
was declared in, not the object the method is called on. Therefore, unbinding or re-binding a method doesn't change the reference of super
in it (although they do change the reference of this
). You can see super
as a variable in the class or object literal scope, which the methods create a closure over. (But also beware that it's not actually a variable, as explained above.)
When setting properties through super
, the property is set on this
instead.
Examples
Using super in classes
This code snippet is taken from the classes sample (live demo). Here super()
is called to avoid duplicating the constructor parts' that are common between Rectangle
and Square
.
class Rectangle {
constructor(height, width) {
this.name = "Rectangle";
this.height = height;
this.width = width;
}
sayName() {
console.log(`Hi, I am a ${this.name}.`);
}
get area() {
return this.height * this.width;
}
set area(value) {
this._area = value;
}
}
class Square extends Rectangle {
constructor(length) {
// Here, it calls the parent class's constructor with lengths
// provided for the Rectangle's width and height
super(length, length);
// Note: In derived classes, super() must be called before you
// can use 'this'. Moving this to the top causes a ReferenceError.
this.name = "Square";
}
}
Super-calling static methods
You are also able to call super on static methods.
class Rectangle {
static logNbSides() {
return "I have 4 sides";
}
}
class Square extends Rectangle {
static logDescription() {
return `${super.logNbSides()} which are all equal`;
}
}
Square.logDescription(); // 'I have 4 sides which are all equal'
Accessing super in class field declaration
super
can also be accessed during class field initialization. The reference of super
depends on whether the current field is an instance field or a static field.
class Base {
static baseStaticField = 90;
baseMethod() {
return 10;
}
}
class Extended extends Base {
extendedField = super.baseMethod(); // 10
static extendedStaticField = super.baseStaticField; // 90
}
Note that instance fields are set on the instance instead of the constructor's prototype
, so you can't use super
to access the instance field of a superclass.
class Base {
baseField = 10;
}
class Extended extends Base {
extendedField = super.baseField; // undefined
}
Here, extendedField
is undefined
instead of 10, because baseField
is defined as an own property of the Base
instance, instead of Base.prototype
. super
, in this context, only looks up properties on Base.prototype
, because that's the [[Prototype]] of Extended.prototype
.
Deleting super properties will throw an error
You cannot use the delete
operator and super.prop
or super[expr]
to delete a parent class' property — it will throw a ReferenceError
.
class Base {
foo() {}
}
class Derived extends Base {
delete() {
delete super.foo; // this is bad
}
}
new Derived().delete(); // ReferenceError: invalid delete involving 'super'.
Using super.prop in object literals
Super can also be used in the object initializer notation. In this example, two objects define a method. In the second object, super
calls the first object's method. This works with the help of Object.setPrototypeOf()
with which we are able to set the prototype of obj2
to obj1
, so that super
is able to find method1
on obj1
.
const obj1 = {
method1() {
console.log("method 1");
},
};
const obj2 = {
method2() {
super.method1();
},
};
Object.setPrototypeOf(obj2, obj1);
obj2.method2(); // Logs "method 1"
Methods that read super.prop do not behave differently when bound to other objects
Accessing super.x
behaves like Reflect.get(Object.getPrototypeOf(objectLiteral), "x", this)
, which means the property is always sought on the object literal/class declaration's prototype, and unbinding and re-binding a method won't change the reference of super
.
class Base {
baseGetX() {
return 1;
}
}
class Extended extends Base {
getX() {
return super.baseGetX();
}
}
const e = new Extended();
console.log(e.getX()); // 1
const { getX } = e;
console.log(getX()); // 1
The same happens in object literals.
const parent1 = { prop: 1 };
const parent2 = { prop: 2 };
const child = {
myParent() {
console.log(super.prop);
},
};
Object.setPrototypeOf(child, parent1);
child.myParent(); // Logs "1"
const myParent = child.myParent;
myParent(); // Still logs "1"
const anotherChild = { __proto__: parent2, myParent };
anotherChild.myParent(); // Still logs "1"
Only resetting the entire inheritance chain will change the reference of super
.
class Base {
baseGetX() {
return 1;
}
static staticBaseGetX() {
return 3;
}
}
class AnotherBase {
baseGetX() {
return 2;
}
static staticBaseGetX() {
return 4;
}
}
class Extended extends Base {
getX() {
return super.baseGetX();
}
static staticGetX() {
return super.staticBaseGetX();
}
}
const e = new Extended();
// Reset instance inheritance
Object.setPrototypeOf(Extended.prototype, AnotherBase.prototype);
console.log(e.getX()); // Logs "2" instead of "1", because the prototype chain has changed
console.log(Extended.staticGetX()); // Still logs "3", because we haven't modified the static part yet
// Reset static inheritance
Object.setPrototypeOf(Extended, AnotherBase);
console.log(Extended.staticGetX()); // Now logs "4"
Calling methods from super
When calling super.prop
as a function, the this
value inside the prop
function is the current this
, not the object that super
points to. For example, the super.getName()
call logs "Extended"
, despite the code looking like it's equivalent to Base.getName()
.
class Base {
static getName() {
console.log(this.name);
}
}
class Extended extends Base {
static getName() {
super.getName();
}
}
Extended.getName(); // Logs "Extended"
This is especially important when interacting with static private elements.
Setting super.prop sets the property on this instead
Setting properties of super
, such as super.x = 1
, behaves like Reflect.set(Object.getPrototypeOf(objectLiteral), "x", 1, this)
. This is one of the cases where understanding super
as simply "reference of the prototype object" falls short, because it actually sets the property on this
instead.
class A {}
class B extends A {
setX() {
super.x = 1;
}
}
const b = new B();
b.setX();
console.log(b); // B { x: 1 }
console.log(Object.hasOwn(b, "x")); // true
super.x = 1
will look for the property descriptor of x
on A.prototype
(and invoke the setters defined there), but the this
value will be set to this
, which is b
in this context. You can read Reflect.set
for more details on the case when target
and receiver
differ.
This means that while methods that get super.prop
are usually not susceptible to changes in the this
context, those that set super.prop
are.
/* Reusing same declarations as above */
const b2 = new B();
b2.setX.call(null); // TypeError: Cannot assign to read only property 'x' of object 'null'
However, super.x = 1
still consults the property descriptor of the prototype object, which means you cannot rewrite non-writable properties, and setters will be invoked.
class X {
constructor() {
// Create a non-writable property
Object.defineProperty(this, "prop", {
configurable: true,
writable: false,
value: 1,
});
}
}
class Y extends X {
constructor() {
super();
}
foo() {
super.prop = 2; // Cannot overwrite the value.
}
}
const y = new Y();
y.foo(); // TypeError: "prop" is read-only
console.log(y.prop); // 1
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-super-keyword |


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

# Original Wiki contributors
mfuji09
velusgautam
fscholz
wbamberg
jameshkramer
Mingun
Sheppy
ethertank
ShimShamSam
evilpie
Sevenspade
Mgjbot
Ptak82
Maian
Dria


Intl.DurationFormat.prototype.format()

Intl.DurationFormat.prototype.format()
Baseline
2025
Newly available
Since March 2025, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
The format()
method of Intl.DurationFormat
instances formats a duration according to the locale and formatting options of this Intl.DurationFormat
object.
Syntax
format(duration)
Parameters
duration
-
The duration object to be formatted. It should include some or all of the following properties:
years
,months
,weeks
,days
,hours
,minutes
,seconds
,milliseconds
,microseconds
,nanoseconds
. Each property's value should be an integer, and their signs should be consistent. This can be aTemporal.Duration
object; see theTemporal.Duration
documentation for more information about these properties.
Return value
A string representing the given duration
formatted according to the locale and formatting options of this Intl.DurationFormat
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()
The following example shows how to create a Duration formatter using the English language.
const duration = {
years: 1,
months: 2,
weeks: 3,
days: 3,
hours: 4,
minutes: 5,
seconds: 6,
milliseconds: 7,
microseconds: 8,
nanoseconds: 9,
};
// Without options, style defaults to "short"
new Intl.DurationFormat("en").format(duration);
// "1 yr, 2 mths, 3 wks, 3 days, 4 hr, 5 min, 6 sec, 7 ms, 8 μs, 9 ns"
// With style set to "long"
new Intl.DurationFormat("en", { style: "long" }).format(duration);
// "1 year, 2 months, 3 weeks, 3 days, 4 hours, 5 minutes, 6 seconds, 7 milliseconds, 8 microseconds, 9 nanoseconds"
// With style set to "narrow"
new Intl.DurationFormat("en", { style: "narrow" }).format(duration);
// "1y 2mo 3w 3d 4h 5m 6s 7ms 8μs 9ns"
Using format() with different locales and styles
const duration = {
hours: 1,
minutes: 46,
seconds: 40,
};
// With style set to "long" and locale "fr-FR"
new Intl.DurationFormat("fr-FR", { style: "long" }).format(duration);
// "1 heure, 46 minutes et 40 secondes"
// With style set to "short" and locale set to "en"
new Intl.DurationFormat("en", { style: "short" }).format(duration);
// "1 hr, 46 min and 40 sec"
// With style set to "short" and locale set to "pt"
new Intl.DurationFormat("pt", { style: "narrow" }).format(duration);
// "1 h 46 min 40 s"
// With style set to "digital" and locale set to "en"
new Intl.DurationFormat("en", { style: "digital" }).format(duration);
// "1:46:40"
// With style set to "digital", locale set to "en", and hours set to "long"
new Intl.DurationFormat("en", { style: "digital", hours: "long" }).format(
duration,
);
// "1 hour, 46:40"
Using format() with the fractionalDigits option
const duration = {
hours: 11,
minutes: 30,
seconds: 12,
milliseconds: 345,
microseconds: 600,
};
new Intl.DurationFormat("en", { style: "digital" }).format(duration);
// "11:30:12.3456"
new Intl.DurationFormat("en", { style: "digital", fractionalDigits: 5 }).format(
duration,
);
// "11:30:12.34560"
new Intl.DurationFormat("en", { style: "digital", fractionalDigits: 3 }).format(
duration,
);
// "11:30:12.346"
Specifications
| Specification |
|---|
| Intl.DurationFormat # sec-Intl.DurationFormat.prototype.format |


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

# Original Wiki contributors
gmanpersona
mfuji09
krvajal
MaximYaskov
fscholz
lionel-rowe
dfmartin
Wind1808
chrisdavidmills
Artoria2e5
dong-jy
zeta12ti
Waldo
ExE-Boss
pre1ude
johnmorseytest007
pepkin88
ross-u
Zearin_Galaurum
bmarkovic
Sheppy
Brettz9
paury
jonasraoni
SphinxKnight
shripal7
Konrud
wbamberg
schalkneethling
Jedipedia
wisgh
kubijo
autra
vandanasamudrala
jacobp100
jameshkramer
nmve
wbhob
madarche
matthung0807
eduardoboucas
whinc
doomsterinc
nickleus
noscripter
andfaulkner
kevinburkeshyp
kevinburke
chris.johnson
Mingun
ziyunfei
mlissner
miller.augusto
georgebatalinski
stevemao
miller_augusto
enaeseth
paul.irish
Nickolay
evilpie


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

# Original Wiki contributors
fscholz
PatrickKettner
nmve


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


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

# Original Wiki contributors
fscholz
mfluehr
minstrel1977
georgeawg
Mingun
toothbrush


Object initializer

Object initializer
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.
An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}
). Objects can also be initialized using Object.create()
or by invoking a constructor function with the new
operator.
Try it
const object1 = { a: "foo", b: 42, c: {} };
console.log(object1.a);
// Expected output: "foo"
const a = "foo";
const b = 42;
const c = {};
const object2 = { a: a, b: b, c: c };
console.log(object2.b);
// Expected output: 42
const object3 = { a, b, c };
console.log(object3.a);
// Expected output: "foo"
Syntax
o = {
a: "foo",
b: 42,
c: {},
1: "number literal property",
"foo:bar": "string literal property",
shorthandProperty,
method(parameters) {
// …
},
get property() {},
set property(value) {},
[expression]: "computed property",
__proto__: prototype,
...spreadProperty,
};
Description
An object initializer is an expression that describes the initialization of an Object
. Objects consist of properties, which are used to describe an object. The values of object properties can either contain primitive data types or other objects.
Object literal syntax vs. JSON
The object literal syntax is not the same as the JavaScript Object Notation (JSON). Although they look similar, there are differences between them:
- JSON only permits property definition using the
"property": value
syntax. The property name must be double-quoted, and the definition cannot be a shorthand. Computed property names are not allowed either. - JSON object property values can only be strings, numbers,
true
,false
,null
, arrays, or another JSON object. This means JSON cannot express methods or non-plain objects likeMap
orRegExp
. - In JSON,
"__proto__"
is a normal property key. In an object literal, it sets the object's prototype.
JSON is a strict subset of the object literal syntax, meaning that every valid JSON text can be parsed as an object literal, and would likely not cause syntax errors. The only exception is that the object literal syntax prohibits duplicate __proto__
keys, which does not apply to JSON.parse()
. The latter treats __proto__
like a normal property and takes the last occurrence as the property's value. The only time when the object value they represent (a.k.a. their semantic) differ is also when the source contains the __proto__
key — for object literals, it sets the object's prototype; for JSON, it's a normal property.
console.log(JSON.parse('{ "__proto__": 0, "__proto__": 1 }')); // {__proto__: 1}
console.log({ "__proto__": 0, "__proto__": 1 }); // SyntaxError: Duplicate __proto__ fields are not allowed in object literals
console.log(JSON.parse('{ "__proto__": {} }')); // { __proto__: {} }
console.log({ "__proto__": {} }); // {} (with {} as prototype)
Examples
Creating objects
An empty object with no properties can be created like this:
const object = {};
However, the advantage of the literal or initializer notation is, that you are able to quickly create objects with properties inside the curly braces. You notate a list of key: value
pairs delimited by commas.
The following code creates an object with three properties and the keys are "foo"
, "age"
and "baz"
. The values of these keys are a string "bar"
, the number 42
, and another object.
const object = {
foo: "bar",
age: 42,
baz: { myProp: 12 },
};
Accessing properties
Once you have created an object, you might want to read or change them. Object properties can be accessed by using the dot notation or the bracket notation. (See property accessors for detailed information.)
object.foo; // "bar"
object["age"]; // 42
object.baz; // {myProp: 12}
object.baz.myProp; // 12
Property definitions
We have already learned how to notate properties using the initializer syntax. Oftentimes, there are variables in your code that you would like to put into an object. You will see code like this:
const a = "foo";
const b = 42;
const c = {};
const o = {
a: a,
b: b,
c: c,
};
There is a shorter notation available to achieve the same:
const a = "foo";
const b = 42;
const c = {};
// Shorthand property names
const o = { a, b, c };
// In other words,
console.log(o.a === { a }.a); // true
Duplicate property names
When using the same name for your properties, the second property will overwrite the first.
const a = { x: 1, x: 2 };
console.log(a); // {x: 2}
After ES2015, duplicate property names are allowed everywhere, including strict mode. You can also have duplicate property names in classes. The only exception is private elements, which must be unique in the class body.
Method definitions
A property of an object can also refer to a function or a getter or setter method.
const o = {
property: function (parameters) {},
get property() {
return 1;
},
set property(value) {},
};
A shorthand notation is available, so that the keyword function
is no longer necessary.
// Shorthand method names
const o = {
property(parameters) {},
};
There is also a way to concisely define generator methods.
const o = {
*generator() {
// …
},
};
Which is equivalent to this ES5-like notation (but note that ECMAScript 5 has no generators):
const o = {
generator: function* () {
// …
},
};
For more information and examples about methods, see method definitions.
Computed property names
The object initializer syntax also supports computed property names. That allows you to put an expression in square brackets []
, that will be computed and used as the property name. This is reminiscent of the bracket notation of the property accessor syntax, which you may have used to read and set properties already.
Now you can use a similar syntax in object literals, too:
// Computed property names
let i = 0;
const a = {
[`foo${++i}`]: i,
[`foo${++i}`]: i,
[`foo${++i}`]: i,
};
console.log(a.foo1); // 1
console.log(a.foo2); // 2
console.log(a.foo3); // 3
const items = ["A", "B", "C"];
const obj = {
[items]: "Hello",
};
console.log(obj); // A,B,C: "Hello"
console.log(obj["A,B,C"]); // "Hello"
const param = "size";
const config = {
[param]: 12,
[`mobile${param.charAt(0).toUpperCase()}${param.slice(1)}`]: 4,
};
console.log(config); // {size: 12, mobileSize: 4}
Spread properties
Object literals support the spread syntax. It copies own enumerable properties from a provided object onto a new object.
Shallow-cloning (excluding prototype
) or merging objects is now possible using a shorter syntax than Object.assign()
.
const obj1 = { foo: "bar", x: 42 };
const obj2 = { foo: "baz", y: 13 };
const clonedObj = { ...obj1 };
// { foo: "bar", x: 42 }
const mergedObj = { ...obj1, ...obj2 };
// { foo: "baz", x: 42, y: 13 }
Warning:
Note that Object.assign()
triggers setters, whereas the spread syntax doesn't!
Prototype setter
A property definition of the form __proto__: value
or "__proto__": value
does not create a property with the name __proto__
. Instead, if the provided value is an object or null
, it points the [[Prototype]]
of the created object to that value. (If the value is not an object or null
, the object is not changed.)
Note that the __proto__
key is standardized syntax, in contrast to the non-standard and non-performant Object.prototype.__proto__
accessors. It sets the [[Prototype]]
during object creation, similar to Object.create
— instead of mutating the prototype chain.
const obj1 = {};
console.log(Object.getPrototypeOf(obj1) === Object.prototype); // true
const obj2 = { __proto__: null };
console.log(Object.getPrototypeOf(obj2)); // null
const protoObj = {};
const obj3 = { "__proto__": protoObj };
console.log(Object.getPrototypeOf(obj3) === protoObj); // true
const obj4 = { __proto__: "not an object or null" };
console.log(Object.getPrototypeOf(obj4) === Object.prototype); // true
console.log(Object.hasOwn(obj4, "__proto__")); // false
Only a single prototype setter is permitted in an object literal. Multiple prototype setters are a syntax error.
Property definitions that do not use "colon" notation are not prototype setters. They are property definitions that behave identically to similar definitions using any other name.
const __proto__ = "variable";
const obj1 = { __proto__ };
console.log(Object.getPrototypeOf(obj1) === Object.prototype); // true
console.log(Object.hasOwn(obj1, "__proto__")); // true
console.log(obj1.__proto__); // "variable"
const obj2 = { __proto__() { return "hello"; } };
console.log(obj2.__proto__()); // "hello"
const obj3 = { ["__proto__"]: 17 };
console.log(obj3.__proto__); // 17
// Mixing prototype setter with normal own properties with "__proto__" key
const obj4 = { ["__proto__"]: 17, __proto__: {} }; // {__proto__: 17} (with {} as prototype)
const obj5 = {
["__proto__"]: 17,
__proto__: {},
__proto__: null, // SyntaxError: Duplicate __proto__ fields are not allowed in object literals
};
const obj6 = {
["__proto__"]: 17,
["__proto__"]: "hello",
__proto__: null,
}; // {__proto__: "hello"} (with null as prototype)
const obj7 = {
["__proto__"]: 17,
__proto__,
__proto__: null,
}; // {__proto__: "variable"} (with null as prototype)
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-object-initializer |

const o = {
  *generator() {
    // …
  },
};


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

# Original Wiki contributors
mfuji09
fscholz
Zearin_Galaurum
alattalatta
wbamberg
jameshkramer
eduardoboucas
ziyunfei
Mingun
ethertank
Sheppy
evilpie
Waldo
Potappo
Mgjbot


TypeError: More arguments needed

TypeError: More arguments needed
The JavaScript exception "more arguments needed" occurs when there is an error with how a function is called. More arguments need to be provided.
Message
TypeError: Object prototype may only be an Object or null: undefined (V8-based) TypeError: Object.create requires at least 1 argument, but only 0 were passed (Firefox) TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 0 were passed (Firefox) TypeError: Object.defineProperties requires at least 1 argument, but only 0 were passed (Firefox) TypeError: Object prototype may only be an Object or null. (Safari)
Error type
What went wrong?
There is an error with how a function is called. More arguments need to be provided.
Examples
Required arguments not provided
The Object.create()
method requires at least one argument and the
Object.setPrototypeOf()
method requires at least two arguments:
js
const obj = Object.create();
// TypeError: Object.create requires at least 1 argument, but only 0 were passed
const obj2 = Object.setPrototypeOf({});
// TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 1 were passed
You can fix this by setting null
as the prototype, for example:
js
const obj = Object.create(null);
const obj2 = Object.setPrototypeOf({}, null);
See also
- Functions guide


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

# Original Wiki contributors
OtterOne
sideshowbarker
BlackBindy
fscholz
snek
Dorward
neverRare
koesper
Zearin_Galaurum
Mik13
wbamberg
SphinxKnight


Temporal.Instant.fromEpochMilliseconds()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
The Temporal.Instant.fromEpochMilliseconds()
static method creates a new Temporal.Instant
object from the number of milliseconds since the Unix epoch (midnight at the beginning of January 1, 1970, UTC).
To convert a Date
object to a Temporal.Instant
object, use Date.prototype.toTemporalInstant()
instead.
Syntax
js
Temporal.Instant.fromEpochMilliseconds(epochMilliseconds)
Parameters
epochMilliseconds
-
A number representing the number of milliseconds since the Unix epoch. Internally, it is converted to a BigInt and multiplied by
1e6
to get the number of nanoseconds.
Return value
A new Temporal.Instant
object representing the instant in time specified by epochMilliseconds
.
Exceptions
RangeError
-
Thrown in one of the following cases:
epochMilliseconds
cannot be converted to a BigInt (e.g., not an integer).epochMilliseconds
is not in the representable range, which is ±108 days, or about ±273,972.6 years, from the Unix epoch.
Examples
Using Temporal.Instant.fromEpochMilliseconds()
js
const instant = Temporal.Instant.fromEpochMilliseconds(0);
console.log(instant.toString()); // 1970-01-01T00:00:00Z
const vostok1Liftoff = Temporal.Instant.fromEpochMilliseconds(-275248380000);
console.log(vostok1Liftoff.toString()); // 1961-04-12T06:07:00Z
const sts1Liftoff = Temporal.Instant.fromEpochMilliseconds(355924804000);
console.log(sts1Liftoff.toString()); // 1981-04-12T12:00:04Z
Specifications
| Specification |
|---|
| Temporal # sec-temporal.instant.fromepochmilliseconds |


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


Remainder (%)

Remainder (%)
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 remainder (%
) operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.
Try it
console.log(13 % 5);
// Expected output: 3
console.log(-13 % 5);
// Expected output: -3
console.log(4 % 2);
// Expected output: 0
console.log(-4 % 2);
// Expected output: -0
Syntax
x % y
Description
The %
operator is overloaded for two types of operands: number and BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt remainder if both operands become BigInts; otherwise, it performs number remainder. A TypeError
is thrown if one operand becomes a BigInt but the other becomes a number.
For the operation n % d
, n
is called the dividend and d
is called the divisor. The operation returns NaN
if one of the operands is NaN
, n
is ±Infinity, or if d
is ±0. Otherwise, if d
is ±Infinity or if n
is ±0, the dividend n
is returned.
When both operands are non-zero and finite, the remainder r
is calculated as r := n - d * q
where q
is the integer such that r
has the same sign as the dividend n
while being as close to 0 as possible.
Note that while in most languages, '%' is a remainder operator, in some (e.g., Python, Perl) it is a modulo operator. Modulo is defined as k := n - d * q
where q
is the integer such that k
has the same sign as the divisor d
while being as close to 0 as possible. For two values of the same sign, the two are equivalent, but when the operands are of different signs, the modulo result always has the same sign as the divisor, while the remainder has the same sign as the dividend, which can make them differ by one unit of d
. To obtain a modulo in JavaScript, in place of n % d
, use ((n % d) + d) % d
. In JavaScript, the modulo operation (which doesn't have a dedicated operator) is used to normalize the second operand of bitwise shift operators (<<
, >>
, etc.), making the offset always a positive value.
For BigInt division, a RangeError
is thrown if the divisor y
is 0n
. This is because number remainder by zero returns NaN
, but BigInt has no concept of NaN
.
Examples
Remainder with positive dividend
13 % 5; // 3
1 % -2; // 1
1 % 2; // 1
2 % 3; // 2
5.5 % 2; // 1.5
3n % 2n; // 1n
Remainder with negative dividend
-13 % 5; // -3
-1 % 2; // -1
-4 % 2; // -0
-3n % 2n; // -1n
Remainder with NaN
NaN % 2; // NaN
Remainder with Infinity
Infinity % 2; // NaN
Infinity % 0; // NaN
Infinity % Infinity; // NaN
2 % Infinity; // 2
0 % Infinity; // 0
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-multiplicative-operators |


Temporal.Now.plainTimeISO()

Temporal.Now.plainTimeISO()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
The Temporal.Now.plainTimeISO()
static method returns the current time as a Temporal.PlainTime
object, in the specified time zone.
Note that although the method contains "ISO" in its name, Temporal.PlainTime
objects do not have associated calendars, as the time format is not calendar-dependent.
Syntax
Temporal.Now.plainTimeISO()
Temporal.Now.plainTimeISO(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 time in the specified time zone, as a Temporal.PlainTime
object. Has the same precision as Temporal.Now.instant()
.
Exceptions
RangeError
-
Thrown if the time zone is invalid.
Examples
Using Temporal.Now.plainTimeISO()
// The current time in the system's time zone
const time = Temporal.Now.plainTimeISO();
console.log(time); // e.g.: 06:12:34.567890123
// The current time in the "America/New_York" time zone
const timeInNewYork = Temporal.Now.plainTimeISO("America/New_York");
console.log(timeInNewYork); // e.g.: 23:12:34.567890123
Specifications
| Specification |
|---|
| Temporal # sec-temporal.now.plaintimeiso |


Subtraction (-)

Subtraction (-)
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The subtraction (-
) operator subtracts the two operands, producing their difference.
Try it
console.log(5 - 3);
// Expected output: 2
console.log(3.5 - 5);
// Expected output: -1.5
console.log(5 - "hello");
// Expected output: NaN
console.log(5 - true);
// Expected output: 4
Syntax
x - y
Description
The -
operator is overloaded for two types of operands: number and BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt subtraction if both operands become BigInts; otherwise, it performs number subtraction. A TypeError
is thrown if one operand becomes a BigInt but the other becomes a number.
Examples
Subtraction using numbers
5 - 3; // 2
3 - 5; // -2
Other non-BigInt values are coerced to numbers:
"foo" - 3; // NaN; "foo" is converted to the number NaN
5 - "3"; // 2; "3" is converted to the number 3
Subtraction using BigInts
2n - 1n; // 1n
You cannot mix BigInt and number operands in subtraction.
2n - 1; // TypeError: Cannot mix BigInt and other types, use explicit conversions
2 - 1n; // TypeError: Cannot mix BigInt and other types, use explicit conversions
To do subtraction with a BigInt and a non-BigInt, convert either operand:
2n - BigInt(1); // 1n
Number(2n) - 1; // 1
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-subtraction-operator-minus |


Nullish coalescing assignment (??=)

Nullish coalescing assignment (??=)
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020.
The nullish coalescing assignment (??=
) operator, also known as the logical nullish assignment operator, only evaluates the right operand and assigns to the left if the left operand is nullish (null
or undefined
).
Try it
const a = { duration: 50 };
a.speed ??= 25;
console.log(a.speed);
// Expected output: 25
a.duration ??= 10;
console.log(a.duration);
// Expected output: 50
Syntax
x ??= y
Description
Nullish coalescing assignment short-circuits, meaning that x ??= y
is equivalent to x ?? (x = y)
, except that the expression x
is only evaluated once.
No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x
being const
:
const x = 1;
x ??= 2;
Neither would the following trigger the setter:
const x = {
get value() {
return 1;
},
set value(v) {
console.log("Setter called");
},
};
x.value ??= 2;
In fact, if x
is not nullish, y
is not evaluated at all.
const x = 1;
x ??= console.log("y evaluated");
// Logs nothing
Examples
Using nullish coalescing assignment
You can use the nullish coalescing assignment operator to apply default values to object properties. Compared to using destructuring and default values, ??=
also applies the default value if the property has value null
.
function config(options) {
options.duration ??= 100;
options.speed ??= 25;
return options;
}
config({ duration: 125 }); // { duration: 125, speed: 25 }
config({}); // { duration: 100, speed: 25 }
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-assignment-operators |


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


Intl.NumberFormat.prototype.formatRangeToParts()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since August 2023.
The formatRangeToParts()
method of Intl.NumberFormat
instances returns an Array
of objects containing the locale-specific tokens from which it is possible to build custom strings while preserving the locale-specific parts. This makes it possible to provide locale-aware custom formatting ranges of number strings.
Syntax
formatRangeToParts(startRange, endRange)
Parameters
startRange
-
A
Number
,BigInt
, or string, to format. Strings are parsed in the same way as in number conversion, except thatformatRangeToParts()
will use the exact value that the string represents, avoiding loss of precision during implicitly conversion to a number. endRange
Return value
An Array
of objects containing the formatted range in parts. Each object has three properties, type
, value
, and source
, each containing a string. The string concatenation of value
, in the order provided, will result in the same string as formatRange()
. The type
may have the same values as formatToParts()
, or the additional value "approximatelySign"
(see below). The source
can be one of the following:
startRange
-
The token is a part of the start number.
endRange
-
The token is a part of the end number.
-
The token is shared between the start and end; for example, the currency symbol. All literals that are part of the range pattern itself, such as the
"–"
separator, are also marked asshared
.
If the start and end numbers are formatted to the same string, then the output has the same list of tokens as calling formatToParts()
on the start number, with all tokens marked as source: "shared"
. In addition, the first token may be an "approximately equals" symbol (e.g., "~") with type: "approximatelySign"
. The insertion of this symbol only depends on the locale settings, and is inserted even when startRange === endRange
.
Exceptions
RangeError
-
Thrown if either
startRange
orendRange
isNaN
or an inconvertible string. TypeError
-
Thrown if either
startRange
orendRange
is undefined.
Examples
Using formatRangeToParts()
The formatRange()
method outputs localized, opaque strings that cannot be manipulated directly:
const startRange = 3500;
const endRange = 9500;
const formatter = new Intl.NumberFormat("de-DE", {
style: "currency",
currency: "EUR",
});
console.log(formatter.formatRange(startRange, endRange));
// "3.500,00–9.500,00 €"
However, in many user interfaces you may want to customize the formatting of this string, or interleave it with other texts. The formatRangeToParts()
method produces the same information in parts:
console.log(formatter.formatRangeToParts(startRange, endRange));
// return value:
[
{ type: "integer", value: "3", source: "startRange" },
{ type: "group", value: ".", source: "startRange" },
{ type: "integer", value: "500", source: "startRange" },
{ type: "decimal", value: ",", source: "startRange" },
{ type: "fraction", value: "00", source: "startRange" },
{ type: "literal", value: "–", source: "shared" },
{ type: "integer", value: "9", source: "endRange" },
{ type: "group", value: ".", source: "endRange" },
{ type: "integer", value: "500", source: "endRange" },
{ type: "decimal", value: ",", source: "endRange" },
{ type: "fraction", value: "00", source: "endRange" },
{ type: "literal", value: " ", source: "shared" },
{ type: "currency", value: "€", source: "shared" },
];
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # sec-intl.numberformat.prototype.formatrangetoparts |


BigInt.prototype.toString()

BigInt.prototype.toString()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020.
The toString()
method of BigInt
values returns a string representing the specified BigInt
value. The trailing "n" is not part of the string.
Try it
console.log(1024n.toString());
// Expected output: "1024"
console.log(1024n.toString(2));
// Expected output: "10000000000"
console.log(1024n.toString(16));
// Expected output: "400"
Syntax
toString()
toString(radix)
Parameters
radix
Optional-
An integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10.
Return value
A string representing the specified BigInt
value.
Exceptions
RangeError
-
Thrown if
radix
is less than 2 or greater than 36.
Description
The BigInt
object overrides the toString
method of Object
; it does not inherit
Object.prototype.toString()
. For BigInt
values, the toString()
method returns a string representation of the value in the specified radix.
For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) a
through f
are used.
If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a -
sign, not the two's complement of the BigInt value.
The toString()
method requires its this
value to be a BigInt
primitive or wrapper object. It throws a TypeError
for other this
values without attempting to coerce them to BigInt values.
Because BigInt
doesn't have a [Symbol.toPrimitive]()
method, JavaScript calls the toString()
method automatically when a BigInt
object is used in a context expecting a string, such as in a template literal. However, BigInt primitive values do not consult the toString()
method to be coerced to strings — rather, they are directly converted using the same algorithm as the initial toString()
implementation.
BigInt.prototype.toString = () => "Overridden";
console.log(`${1n}`); // "1"
console.log(`${Object(1n)}`); // "Overridden"
Examples
Using toString()
17n.toString(); // "17"
66n.toString(2); // "1000010"
254n.toString(16); // "fe"
(-10n).toString(2); // "-1010"
(-0xffn).toString(2); // "-11111111"
Negative-zero BigInt
There is no negative-zero BigInt
as there are no negative zeros in integers. -0.0
is an IEEE floating-point concept that only appears in the JavaScript Number
type.
(-0n).toString(); // "0"
BigInt(-0).toString(); // "0"
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-bigint.prototype.tostring |


TypeError: Reduce of empty array with no initial value
The JavaScript exception "reduce of empty array with no initial value" occurs when a reduce function is used.
Message
TypeError: Reduce of empty array with no initial value (V8-based & Firefox & Safari)
Error type
TypeError
What went wrong?
In JavaScript, there are several reduce functions:
Array.prototype.reduce()
,Array.prototype.reduceRight()
andTypedArray.prototype.reduce()
,TypedArray.prototype.reduceRight()
).
These functions optionally take an initialValue
(which will be used as the
first argument to the first call of the callback
). However, if no initial
value is provided, it will use the first element of the Array
or
TypedArray
as the initial value. This error is raised when an empty array
is provided because no initial value can be returned in that case.
Examples
Invalid cases
This problem appears frequently when combined with a filter
(Array.prototype.filter()
, TypedArray.prototype.filter()
)
which will remove all elements of the list. Thus leaving none to be used as the initial
value.
const ints = [0, -1, -2, -3, -4, -5];
ints
.filter((x) => x > 0) // removes all elements
.reduce((x, y) => x + y); // no more elements to use for the initial value.
Similarly, the same issue can happen if there is a typo in a selector, or an unexpected number of elements in a list:
const names = document.getElementsByClassName("names");
const nameList = Array.prototype.reduce.call(
names,
(acc, name) => `${acc}, ${name}`,
);
Valid cases
These problems can be solved in two different ways.
One way is to actually provide an initialValue
as the neutral element of
the operator, such as 0 for the addition, 1 for a multiplication, or an empty string for
a concatenation.
const ints = [0, -1, -2, -3, -4, -5];
ints
.filter((x) => x > 0) // removes all elements
.reduce((x, y) => x + y, 0); // the initial value is the neutral element of the addition
Another way would be to handle the empty case, either before calling
reduce
, or in the callback after adding an unexpected dummy initial value.
const names = document.getElementsByClassName("names");
let nameList1 = "";
if (names.length >= 1) {
nameList1 = Array.prototype.reduce.call(
names,
(acc, name) => `${acc}, ${name}`,
);
}
// nameList1 === "" when names is empty.
const nameList2 = Array.prototype.reduce.call(
names,
(acc, name) => {
if (acc === "")
// initial value
return name;
return `${acc}, ${name}`;
},
"",
);
// nameList2 === "" when names is empty.


Warning: unreachable code after return statement
The JavaScript warning "unreachable code after return statement" occurs when using an
expression after a return
statement, or when using a
semicolon-less return statement but including an expression directly after.
Message
Warning: unreachable code after return statement (Firefox)
Error type
Warning
What went wrong?
Unreachable code after a return statement might occur in these situations:
- When using an expression after a
return
statement, or - when using a semicolon-less return statement but including an expression directly after.
When an expression exists after a valid return
statement, a warning is
given to indicate that the code after the return
statement is unreachable,
meaning it can never be run.
Why should I have semicolons after return
statements? In the case of
semicolon-less return
statements, it can be unclear whether the developer
intended to return the statement on the following line, or to stop execution and return.
The warning indicates that there is ambiguity in the way the return
statement is written.
Warnings will not be shown for semicolon-less returns if these statements follow it:
Examples
Invalid cases
function f() {
let x = 3;
x += 4;
return x; // return exits the function immediately
x -= 3; // so this line will never run; it is unreachable
}
function g() {
return // this is treated like `return;`
3 + 4; // so the function returns, and this line is never reached
}
Valid cases
function f() {
let x = 3;
x += 4;
x -= 3;
return x; // OK: return after all other statements
}
function g() {
return 3 + 4 // OK: semicolon-less return with expression on the same line
}


Intl.Collator.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.Collator
instances returns a new object with properties reflecting the options computed during initialization of this Collator
object.
Try it
const numberDe = new Intl.NumberFormat("de-DE");
const numberAr = new Intl.NumberFormat("ar");
console.log(numberDe.resolvedOptions().numberingSystem);
// Expected output: "latn"
console.log(numberAr.resolvedOptions().numberingSystem);
// Expected output: "arab"
Syntax
resolvedOptions()
Parameters
None.
Return value
A new object with properties reflecting the options computed during the initialization of this Collator
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
co
,kn
, andkf
Unicode extension keys, if requested and supported, may be included in the output. usage
-
The value provided for this property in the
options
argument, with default filled in as needed. It is either"sort"
or"search"
. The default is"sort"
. sensitivity
-
The value provided for this property in the
options
argument, with default filled in as needed. It is either"base"
,"accent"
,"case"
, or"variant"
. The default is"variant"
for usage"sort"
; it's locale dependent for usage"search"
. ignorePunctuation
-
The value provided for this property in the
options
argument, with default filled in as needed. It is a boolean. The default istrue
for Thai (th
) andfalse
for all other languages. collation
-
The value provided for this property in the
options
argument, or using the Unicode extension key"co"
, with default filled in as needed. It is a supported collation type for this locale. The default is"default"
. numeric
-
The value provided for this property in the
options
argument, or using the Unicode extension key"kn"
, with default filled in as needed. It is a boolean. The default isfalse
. If the implementation does not support this Unicode extension key, this property is omitted. caseFirst
-
The value provided for this property in the
options
argument, or using the Unicode extension key"kf"
, with default filled in as needed. It is either"upper"
,"lower"
, or"false"
. The default is"false"
. If the implementation does not support this Unicode extension key, this property is omitted.
Examples
Using the resolvedOptions method
const de = new Intl.Collator("de", { sensitivity: "base" });
const usedOptions = de.resolvedOptions();
usedOptions.locale; // "de"
usedOptions.usage; // "sort"
usedOptions.sensitivity; // "base"
usedOptions.ignorePunctuation; // false
usedOptions.collation; // "default"
usedOptions.numeric; // false
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # sec-intl.collator.prototype.resolvedoptions |


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

# Original Wiki contributors
mfuji09
wbamberg
fscholz
benaston
nakhodkiin
ihanson
vinyldarkscratch
Yialo
rkoeninger
yg448
snuggs
pmdartus
Sheppy
christophe.hurpeau
minstrel1977
jameshkramer
Velenir
ZeroUnderscoreOu
david_ross
darrenburgess
nmve
kdex
about-code
xfq
mata007
jleedev
jpmedley
reecehudson
bergus
fastest963
Mingun
Qantas94Heavy
ethertank
ziyunfei
fasttime
evilpie
Sevenspade
Nickolay
Andrea@3site.it
Seant23
Andreas Wuest


String: length

String: length
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The length
data property of a String
value contains the length of the string in UTF-16 code units.
Try it
const str = "Life, the universe and everything. Answer:";
console.log(`${str} ${str.length}`);
// Expected output: "Life, the universe and everything. Answer: 42"
Value
A non-negative integer.
Property attributes of String: length | |
|---|---|
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
This property returns the number of code units in the string. JavaScript uses UTF-16 encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by length
to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, mathematical symbols, or obscure Chinese characters, you may need to account for the difference between code units and characters.
The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for precise integers. However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer.
- In V8 (used by Chrome and Node), the maximum length is 229 - 24 (~1GiB). On 32-bit systems, the maximum length is 228 - 16 (~512MiB).
- In Firefox, the maximum length is 230 - 2 (~2GiB). Before Firefox 65, the maximum length was 228 - 1 (~512MiB).
- In Safari, the maximum length is 231 - 1 (~4GiB).
If you are working with large strings in other encodings (such as UTF-8 files or blobs), note that when you load the data into a JS string, the encoding always becomes UTF-16. The size of the string may be different from the size of the source file.
const str1 = "a".repeat(2 ** 29 - 24); // Success
const str2 = "a".repeat(2 ** 29 - 23); // RangeError: Invalid string length
const buffer = new Uint8Array(2 ** 29 - 24).fill("a".codePointAt(0)); // This buffer is 512MiB in size
const str = new TextDecoder().decode(buffer); // This string is 1GiB in size
For an empty string, length
is 0.
The static property String.length
is unrelated to the length of strings. It's the arity of the String
function (loosely, the number of formal parameters it has), which is 1.
Since length
counts code units instead of characters, if you want to get the number of characters, you can first split the string with its iterator, which iterates by characters:
function getCharacterLength(str) {
// The string iterator that is used here iterates over characters,
// not mere code units
return [...str].length;
}
console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3
If you want to count characters by grapheme clusters, use Intl.Segmenter
. You can first pass the string you want to split to the segment()
method, and then iterate over the returned Segments
object to get the length:
function getGraphemeCount(str) {
const segmenter = new Intl.Segmenter("en-US", { granularity: "grapheme" });
// The Segments object iterator that is used here iterates over characters in grapheme clusters,
// which may consist of multiple Unicode characters
return [...segmenter.segment(str)].length;
}
console.log(getGraphemeCount("👨👩👧👧")); // 1
Examples
Basic usage
const x = "Mozilla";
const empty = "";
console.log(`${x} is ${x.length} code units long`);
// Mozilla is 7 code units long
console.log(`The empty string has a length of ${empty.length}`);
// The empty string has a length of 0
Strings with length not equal to the number of characters
const emoji = "😄";
console.log(emoji.length); // 2
console.log([...emoji].length); // 1
const adlam = "𞤲𞥋𞤣𞤫";
console.log(adlam.length); // 8
console.log([...adlam].length); // 4
const formula = "∀𝑥∈ℝ,𝑥²≥0";
console.log(formula.length); // 11
console.log([...formula].length); // 9
Assigning to length
Because string is a primitive, attempting to assign a value to a string's length
property has no observable effect, and will throw in strict mode.
const myString = "bluebells";
myString.length = 4;
console.log(myString); // "bluebells"
console.log(myString.length); // 9
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-properties-of-string-instances-length |


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

# Original Wiki contributors
fscholz
wbamberg
chrisdavidmills
jameshkramer
eduardoboucas
Mingun
Sheppy
evilpie
Mgjbot
Diablownik
Maian
Dria


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

# Original Wiki contributors
mfuji09
chrisdavidmills
fscholz
alattalatta
stmoreau
wbamberg
jameshkramer
eduardoboucas
mhubenthal
Mingun
Sheppy
Norbert
ethertank
Yuichirou
Ptak82
Nickolay
Maian


String() constructor

String() constructor
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The String()
constructor creates String
objects. When called as a function, it returns primitive values of type String.
Syntax
new String(thing)
String(thing)
Note:
String()
can be called with or without new
, but with different effects. See Return value.
Parameters
thing
-
Anything to be converted to a string.
Return value
When String()
is called as a function (without new
), it returns value
coerced to a string primitive. Specially, Symbol values are converted to "Symbol(description)"
, where description
is the description of the Symbol, instead of throwing.
When String()
is called as a constructor (with new
), it coerces value
to a string primitive (without special symbol handling) and returns a wrapping String
object, which is not a primitive.
Warning:
You should rarely find yourself using String
as a constructor.
Examples
String constructor and String function
String function and String constructor produce different results:
const a = new String("Hello world"); // a === "Hello world" is false
const b = String("Hello world"); // b === "Hello world" is true
a instanceof String; // is true
b instanceof String; // is false
typeof a; // "object"
typeof b; // "string"
Here, the function produces a string (the primitive type) as promised. However, the constructor produces an instance of the type String (an object wrapper) and that's why you rarely want to use the String constructor at all.
Using String() to stringify a symbol
String()
is the only case where a symbol can be converted to a string without throwing, because it's very explicit.
const sym = Symbol("example");
`${sym}`; // TypeError: Cannot convert a Symbol value to a string
"" + sym; // TypeError: Cannot convert a Symbol value to a string
"".concat(sym); // TypeError: Cannot convert a Symbol value to a string
const sym = Symbol("example");
String(sym); // "Symbol(example)"
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-string-constructor |
Browser compatibility
See also
- Numbers and strings guide


JSON.rawJSON()

JSON.rawJSON()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
The JSON.rawJSON()
static method creates a "raw JSON" object containing a piece of JSON text. When serialized to JSON, the raw JSON object is treated as if it is already a piece of JSON. This text is required to be valid JSON.
Syntax
JSON.rawJSON(string)
Parameters
string
-
The JSON text. Must be valid JSON representing a primitive value.
Return value
An object that can be used to create JSON text with the exact same content as the string
provided, without quotes around the string itself. This object has null
prototype and is frozen (so it never gets accidentally serialized as a regular object by any kind of primitive conversion), and the following property:
rawJSON
-
The original JSON
string
provided.
Furthermore, it has a private field that marks itself as a raw JSON object. This allows it to be identified by JSON.stringify()
and JSON.isRawJSON()
.
Exceptions
SyntaxError
-
Thrown if the
string
is not valid JSON, or if it represents an object or array.
Description
A raw JSON object can be seen as an immutable, atomic data structure like any kind of primitive. It is not a regular object and it contains no data other than the raw JSON text. It is used to "pre-serialize" data to formats that JSON.stringify
itself cannot produce for various reasons. The most typical use case is the floating point number loss of precision problem. For example:
JSON.stringify({ value: 12345678901234567890 });
// {"value":12345678901234567000}
The value is not exactly equivalent to the original number any more! This is because JavaScript uses floating point representation for all numbers, so it cannot represent all integers exactly. The number literal 12345678901234567890
itself is already rounded to the nearest representable number when it is parsed by JavaScript.
Without JSON.rawJSON
, there is no way to tell JSON.stringify
to produce the number literal 12345678901234567890
, because there is simply no corresponding JavaScript number value. With raw JSON, you can directly tell JSON.stringify()
what a particular value should be stringified as:
const rawJSON = JSON.rawJSON("12345678901234567890");
JSON.stringify({ value: rawJSON });
// {"value":12345678901234567890}
For a more complete example of this, see Lossless number serialization.
Note that although we passed a string to JSON.rawJSON()
, it still becomes a number in the final JSON. This is because the string represents the verbatim JSON text. If you want to serialize a string, you should use JSON.rawJSON()
with a quotes-enclosed string value:
const rawJSON = JSON.rawJSON('"Hello world"');
JSON.stringify({ value: rawJSON });
// {"value":"Hello world"}
JSON.rawJSON
allows you to insert arbitrary JSON text, but does not allow you to create invalid JSON. Anything that was not permitted by the JSON syntax is not permitted by JSON.rawJSON()
either:
const rawJSON = JSON.rawJSON('"Hello\nworld"'); // Syntax error, because line breaks are not allowed in JSON strings
Furthermore, you cannot use JSON.rawJSON()
to create JSON objects or arrays.
Examples
Using JSON.rawJSON() to create JSON expressions of different types
const numJSON = JSON.rawJSON("123");
const strJSON = JSON.rawJSON('"Hello world"');
const boolJSON = JSON.rawJSON("true");
const nullJSON = JSON.rawJSON("null");
console.log(
JSON.stringify({
age: numJSON,
message: strJSON,
isActive: boolJSON,
nothing: nullJSON,
}),
);
// {"age":123,"message":"Hello world","isActive":true,"nothing":null}
However, you cannot use JSON.rawJSON()
to create JSON objects or arrays:
const arrJSON = JSON.rawJSON("[1, 2, 3]");
const objJSON = JSON.rawJSON('{"a": 1, "b": 2}');
// SyntaxError
Using JSON.rawJSON() to create escaped string literals
Apart from numbers, there is only one other type that does not have a one-to-one correspondence between JavaScript values and JSON text: strings. When strings are serialized to JSON, all code points, other than those that are not legal inside JSON string literals (such as line breaks), are printed literally:
console.log(JSON.stringify({ value: "\ud83d\ude04" })); // {"value":"😄"}
This may not be desirable, because the receiver of this string may handle Unicode differently. To improve interoperability, you can explicitly specify the string to be serialized with escape sequences:
const rawJSON = JSON.rawJSON('"\\ud83d\\ude04"');
const objStr = JSON.stringify({ value: rawJSON });
console.log(objStr); // {"value":"\ud83d\ude04"}
console.log(JSON.parse(objStr).value); // 😄
Note that the double backslashes in the rawJSON
actually represents a single slash character.
Specifications
| Specification |
|---|
| JSON.parse source text access # sec-json.rawjson |


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

# Original Wiki contributors
hinell
jridgewell
fscholz


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

# Original Wiki contributors
mfuji09
fscholz
schalkneethling
jameshkramer
eduardoboucas
Mingun
ethertank
Sheppy
evilpie
Ptak82
Maian
Dria


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

# Original Wiki contributors
wbamberg
fscholz
SphinxKnight
rwe2020
sideshowbarker


Remainder assignment (%=)

Remainder assignment (%=)
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The remainder assignment (%=
) operator performs remainder on the two operands and assigns the result to the left operand.
Try it
let a = 3;
console.log((a %= 2));
// Expected output: 1
console.log((a %= 0));
// Expected output: NaN
console.log((a %= "hello"));
// Expected output: NaN
Syntax
js
x %= y
Description
x %= y
is equivalent to x = x % y
, except that the expression x
is only evaluated once.
Examples
Using remainder assignment
js
let bar = 5;
bar %= 2; // 1
bar %= "foo"; // NaN
bar %= 0; // NaN
let foo = 3n;
foo %= 2n; // 1n
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-assignment-operators |


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

# Original Wiki contributors
fscholz
SphinxKnight
th0rgall
PatrickKettner
WangNianyi2001
nbp


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


Temporal.Duration.prototype.hours

Temporal.Duration.prototype.hours
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
The hours
accessor property of Temporal.Duration
instances returns an integer representing the number of hours 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 hours, the hours
absolute value will be between 0 and 23, inclusive.
The set accessor of hours
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 hours
js
const d1 = Temporal.Duration.from({ hours: 1, minutes: 30 });
const d2 = Temporal.Duration.from({ hours: -1, minutes: -30 });
const d3 = Temporal.Duration.from({ days: 1 });
const d4 = Temporal.Duration.from({ hours: 24 });
console.log(d1.hours); // 1
console.log(d2.hours); // -1
console.log(d3.hours); // 0
console.log(d4.hours); // 24
// Balance d4
const d4Balanced = d4.round({ largestUnit: "days" });
console.log(d4Balanced.hours); // 0
console.log(d4Balanced.days); // 1
Specifications
| Specification |
|---|
| Temporal # sec-get-temporal.duration.prototype.hours |
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.minutes
Temporal.Duration.prototype.seconds
Temporal.Duration.prototype.milliseconds
Temporal.Duration.prototype.microseconds
Temporal.Duration.prototype.nanoseconds


Warning: -file- is being assigned a //# sourceMappingURL, but already has one
The JavaScript warning "-file- is being assigned a //# sourceMappingURL, but already has one." occurs when a source map has been specified more than once for a given JavaScript source.
Message
Warning: -file- is being assigned a //# sourceMappingURL, but already has one.
Error type
A warning. JavaScript execution won't be halted.
What went wrong?
A source map has been specified more than once for a given JavaScript source.
JavaScript sources are often combined and minified to make delivering them from the server more efficient. With source maps, the debugger can map the code being executed to the original source files. There are two ways to assign a source map, either by using a comment or by setting a header to the JavaScript file.
Examples
Setting source maps
Setting a source map by using a comment in the file:
js
//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map
Or, alternatively, you can set a header to your JavaScript file:
http
X-SourceMap: /path/to/file.js.map
See also
- Use a source map in the Firefox source docs
- Introduction to JavaScript source maps on developer.chrome.com (2012)


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

# Original Wiki contributors
wbamberg
fscholz
chrisdavidmills


Property accessors

Property accessors
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.
Property accessors provide access to an object's properties by using the dot notation or the bracket notation.
Try it
const person1 = {};
person1["firstName"] = "Mario";
person1["lastName"] = "Rossi";
console.log(person1.firstName);
// Expected output: "Mario"
const person2 = {
firstName: "John",
lastName: "Doe",
};
console.log(person2["lastName"]);
// Expected output: "Doe"
Syntax
object.propertyName
object[expression]
object.#privateProperty
Description
One can think of an object as an associative array (a.k.a. map, dictionary, hash, lookup table). The keys in this array are the names of the object's properties.
There are two ways to access properties: dot notation and bracket notation.
Dot notation
In the object.propertyName
syntax, the propertyName
must be a valid JavaScript identifier which can also be a reserved word. For example, object.$1
is valid, while object.1
is not.
const variable = object.propertyName;
object.propertyName = value;
const object = {};
object.$1 = "foo";
console.log(object.$1); // 'foo'
const object = {};
object.1 = "bar"; // SyntaxError
console.log(object.1); // SyntaxError
Here, the method named createElement
is retrieved from document
and is called.
document.createElement("pre");
If you use a method for a numeric literal, and the numeric literal has no exponent and no decimal point, you should leave white-space(s) before the dot preceding the method call, so that the dot is not interpreted as a decimal point.
77 .toExponential();
// or
77
.toExponential();
// or
(77).toExponential();
// or
77..toExponential();
// or
77.0.toExponential();
// because 77. === 77.0, no ambiguity
In addition, private elements can only be accessed using dot notation within the class that defines them.
Bracket notation
In the object[expression]
syntax, the expression
should evaluate to a string or Symbol that represents the property's name. So, it can be any string literal, for example, including '1foo'
, '!bar!'
, or even ' '
(a space).
const variable = object[propertyName];
object[propertyName] = value;
This does the exact same thing as the previous example.
document["createElement"]("pre");
A space before bracket notation is allowed.
document ["createElement"]("pre");
Passing expressions that evaluate to property name will do the same thing as directly passing the property name.
const key = "name";
const getKey = () => "name";
const Obj = { name: "Michel" };
Obj["name"]; // returns "Michel"
Obj[key]; // evaluates to Obj["name"], and returns "Michel"
Obj[getKey()]; // evaluates to Obj["name"], and returns "Michel"
However, beware of using square brackets to access properties whose names are given by external input. This may make your code susceptible to object injection attacks.
Property names
Each property name is a string or a Symbol. Any other value, including a number, is coerced to a string. This outputs 'value'
, since 1
is coerced into '1'
.
const object = {};
object["1"] = "value";
console.log(object[1]);
This also outputs 'value'
, since both foo
and bar
are converted to the same string ("[object Object]"
).
const foo = { uniqueProp: 1 };
const bar = { uniqueProp: 2 };
const object = {};
object[foo] = "value";
console.log(object[bar]);
Method binding
It's typical when speaking of an object's properties to make a distinction between properties and methods. However, the property/method distinction is little more than a convention. A method is a property that can be called (for example, if it has a reference to a Function
instance as its value).
A method is not bound to the object that it is a property of. Specifically, this
is not fixed in a method and does not necessarily refer to the object containing the method. Instead, this
is "passed" by the function call. See the reference for this
.
Examples
Bracket notation vs. eval()
JavaScript novices often make the mistake of using eval()
where the bracket notation can be used instead.
For example, the following syntax is often seen in many scripts.
const x = eval(`document.forms.form_name.elements.${strFormControl}.value`);
eval()
is slow and should be avoided whenever possible. Also, strFormControl
would have to hold an identifier, which is not required for names and id
s of form controls. It is better to use bracket notation instead:
const x = document.forms.form_name.elements[strFormControl].value;
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-property-accessors |


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

# Original Wiki contributors
fscholz
yhakina1114
rolfedh
jorendorff-moz
clarkbdubya


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


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


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


Object.prototype.toLocaleString()

Object.prototype.toLocaleString()
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 toLocaleString()
method of Object
instances returns a string representing this object. This method is meant to be overridden by derived objects for locale-specific purposes.
Try it
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
console.log(date.toLocaleString("ar-EG"));
// Expected output: "٢٠/١٢/٢٠١٢ ٤:٠٠:٠٠ ص"
const number = 123456.789;
console.log(number.toLocaleString("de-DE"));
// Expected output: "123.456,789"
Syntax
toLocaleString()
Parameters
None. However, all objects that override this method are expected to accept at most two parameters, corresponding to locales
and options
, such as Number.prototype.toLocaleString
. The parameter positions should not be used for any other purpose.
Return value
The return value of calling this.toString()
.
Description
All objects that inherit from Object.prototype
(that is, all except null
-prototype objects) inherit the toLocaleString()
method. Object
's toLocaleString
returns the result of calling this.toString()
.
This function is provided to give objects a generic toLocaleString
method, even though not all may use it. In the core language, these built-in objects override toLocaleString
to provide locale-specific formatting:
Examples
Using the base toLocaleString() method
The base toLocaleString()
method simply calls toString()
.
const obj = {
toString() {
return "My Object";
},
};
console.log(obj.toLocaleString()); // "My Object"
Array toLocaleString() override
Array.prototype.toLocaleString()
is used to print array values as a string by invoking each element's toLocaleString()
method and joining the results with a locale-specific separator. For example:
const testArray = [4, 7, 10];
const euroPrices = testArray.toLocaleString("fr", {
style: "currency",
currency: "EUR",
});
// "4,00 €,7,00 €,10,00 €"
Date toLocaleString() override
Date.prototype.toLocaleString()
is used to print out date displays more suitable for specific locales. For example:
const testDate = new Date();
// "Fri May 29 2020 18:04:24 GMT+0100 (British Summer Time)"
const deDate = testDate.toLocaleString("de");
// "29.5.2020, 18:04:24"
const frDate = testDate.toLocaleString("fr");
// "29/05/2020, 18:04:24"
Number toLocaleString() override
Number.prototype.toLocaleString()
is used to print out number displays more suitable for specific locales, e.g., with the correct separators. For example:
const testNumber = 2901234564;
// "2901234564"
const deNumber = testNumber.toLocaleString("de");
// "2.901.234.564"
const frNumber = testNumber.toLocaleString("fr");
// "2 901 234 564"
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-object.prototype.tolocalestring |


BigInt.prototype.toLocaleString()

BigInt.prototype.toLocaleString()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020.
The toLocaleString()
method of BigInt
values returns a string with a language-sensitive representation of this BigInt. In implementations with Intl.NumberFormat
API support, this method delegates to Intl.NumberFormat
.
Every time toLocaleString
is called, it has to perform a search in a big database of localization strings, which is potentially inefficient. When the method is called many times with the same arguments, it is better to create an Intl.NumberFormat
object and use its format()
method, because a NumberFormat
object remembers the arguments passed to it and may decide to cache a slice of the database, so future format
calls can search for localization strings within a more constrained context.
Try it
const bigint = 123456789123456789n;
// German uses period for thousands
console.log(bigint.toLocaleString("de-DE"));
// Expected output: "123.456.789.123.456.789"
// Request a currency format
console.log(
bigint.toLocaleString("de-DE", { style: "currency", currency: "EUR" }),
);
// Expected output: "123.456.789.123.456.789,00 €"
Syntax
toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)
Parameters
The locales
and options
parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.
In implementations that support the Intl.NumberFormat
API, these parameters correspond exactly to the Intl.NumberFormat()
constructor's parameters. Implementations without Intl.NumberFormat
support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.
locales
Optional-
A string with a BCP 47 language tag, or an array of such strings. Corresponds to the
locales
parameter of theIntl.NumberFormat()
constructor.In implementations without
Intl.NumberFormat
support, this parameter is ignored and the host's locale is usually used. options
Optional-
An object adjusting the output format. Corresponds to the
options
parameter of theIntl.NumberFormat()
constructor.In implementations without
Intl.NumberFormat
support, this parameter is ignored.
See the Intl.NumberFormat()
constructor for details on these parameters and how to use them.
Return value
A string representing the given BigInt according to language-specific conventions.
In implementations with Intl.NumberFormat
, this is equivalent to new Intl.NumberFormat(locales, options).format(number)
.
Note:
Most of the time, the formatting returned by toLocaleString()
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 toLocaleString()
to hardcoded constants.
Examples
Using toLocaleString()
Basic use of this method without specifying a locale
returns a formatted string in the default locale and with default options.
const bigint = 3500n;
console.log(bigint.toLocaleString());
// "3,500" if in U.S. English locale
Checking for support for locales and options parameters
The locales
and options
parameters may not be supported in all implementations, because support for the internationalization API is optional, and some systems may not have the necessary data. For implementations without internationalization support, toLocaleString()
always uses the system's locale, which may not be what you want. Because any implementation that supports the locales
and options
parameters must support the Intl
API, you can check the existence of the latter for support:
function toLocaleStringSupportsLocales() {
return (
typeof Intl === "object" &&
!!Intl &&
typeof Intl.NumberFormat === "function"
);
}
Using locales
This example shows some of the variations in localized number formats. In order to get
the format of the language used in the user interface of your application, make sure to
specify that language (and possibly some fallback languages) using the
locales
argument:
const bigint = 123456789123456789n;
// German uses period for thousands
console.log(bigint.toLocaleString("de-DE"));
// 123.456.789.123.456.789
// Arabic in most Arabic speaking countries uses Eastern Arabic digits
console.log(bigint.toLocaleString("ar-EG"));
// ١٢٣٬٤٥٦٬٧٨٩٬١٢٣٬٤٥٦٬٧٨٩
// India uses thousands/lakh/crore separators
console.log(bigint.toLocaleString("en-IN"));
// 1,23,45,67,89,12,34,56,789
// the nu extension key requests a numbering system, e.g. Chinese decimal
console.log(bigint.toLocaleString("zh-Hans-CN-u-nu-hanidec"));
// 一二三,四五六,七八九,一二三,四五六,七八九
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(bigint.toLocaleString(["ban", "id"]));
// 123.456.789.123.456.789
Using options
The results provided by toLocaleString()
can be customized using the options
parameter:
const bigint = 123456789123456789n;
// request a currency format
console.log(
bigint.toLocaleString("de-DE", { style: "currency", currency: "EUR" }),
);
// 123.456.789.123.456.789,00 €
// the Japanese yen doesn't use a minor unit
console.log(
bigint.toLocaleString("ja-JP", { style: "currency", currency: "JPY" }),
);
// ￥123,456,789,123,456,789
// limit to three significant digits
console.log(bigint.toLocaleString("en-IN", { maximumSignificantDigits: 3 }));
// 1,23,00,00,00,00,00,00,000
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # sup-bigint.prototype.tolocalestring |


Object.prototype.__proto__

Object.prototype.__proto__
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
Warning:
Changing the [[Prototype]]
of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the obj.__proto__ = ...
statement, but may extend to any code that has access to any object whose [[Prototype]]
has been altered. You can read more in JavaScript engine fundamentals: optimizing prototypes.
Note:
The use of __proto__
is controversial and discouraged. Its existence and exact behavior have only been standardized as a legacy feature to ensure web compatibility, while it presents several security issues and footguns. For better support, prefer Object.getPrototypeOf()
/Reflect.getPrototypeOf()
and Object.setPrototypeOf()
/Reflect.setPrototypeOf()
instead.
The __proto__
accessor property of Object
instances exposes the [[Prototype]]
(either an object or null
) of this object.
The __proto__
property can also be used in an object literal definition to set the object [[Prototype]]
on creation, as an alternative to Object.create()
. See: object initializer / literal syntax. That syntax is standard and optimized for in implementations, and quite different from Object.prototype.__proto__
.
Syntax
obj.__proto__
Return value
If used as a getter, returns the object's [[Prototype]]
.
Exceptions
TypeError
-
Thrown if attempting to set the prototype of a non-extensible object or an immutable prototype exotic object, such as
Object.prototype
orwindow
.
Description
The __proto__
getter function exposes the value of the internal [[Prototype]]
of an object. For objects created using an object literal (unless you use the prototype setter syntax), this value is Object.prototype
. For objects created using array literals, this value is Array.prototype
. For functions, this value is Function.prototype
. You can read more about the prototype chain in Inheritance and the prototype chain.
The __proto__
setter allows the [[Prototype]]
of an object to be mutated. The value provided must be an object or null
. Providing any other value will do nothing.
Unlike Object.getPrototypeOf()
and Object.setPrototypeOf()
, which are always available on Object
as static properties and always reflect the [[Prototype]]
internal property, the __proto__
property doesn't always exist as a property on all objects, and as a result doesn't reflect [[Prototype]]
reliably.
The __proto__
property is just an accessor property on Object.prototype
consisting of a getter and setter function. A property access for __proto__
that eventually consults Object.prototype
will find this property, but an access that does not consult Object.prototype
will not. If some other __proto__
property is found before Object.prototype
is consulted, that property will hide the one found on Object.prototype
.
null
-prototype objects don't inherit any property from Object.prototype
, including the __proto__
accessor property, so if you try to read __proto__
on such an object, the value is always undefined
regardless of the object's actual [[Prototype]]
, and any assignment to __proto__
would create a new property called __proto__
instead of setting the object's prototype. Furthermore, __proto__
can be redefined as an own property on any object instance through Object.defineProperty()
without triggering the setter. In this case, __proto__
will no longer be an accessor for [[Prototype]]
. Therefore, always prefer Object.getPrototypeOf()
and Object.setPrototypeOf()
for setting and getting the [[Prototype]]
of an object.
Examples
Using __proto__
function Circle() {}
const shape = {};
const circle = new Circle();
// Set the object prototype.
// DEPRECATED. This is for example purposes only. DO NOT DO THIS in real code.
shape.__proto__ = circle;
// Get the object prototype
console.log(shape.__proto__ === Circle); // false
function ShapeA() {}
const ShapeB = {
a() {
console.log("aaa");
},
};
ShapeA.prototype.__proto__ = ShapeB;
console.log(ShapeA.prototype.__proto__); // { a: [Function: a] }
const shapeA = new ShapeA();
shapeA.a(); // aaa
console.log(ShapeA.prototype === shapeA.__proto__); // true
function ShapeC() {}
const ShapeD = {
a() {
console.log("a");
},
};
const shapeC = new ShapeC();
shapeC.__proto__ = ShapeD;
shapeC.a(); // a
console.log(ShapeC.prototype === shapeC.__proto__); // false
function Test() {}
Test.prototype.myName = function () {
console.log("myName");
};
const test = new Test();
console.log(test.__proto__ === Test.prototype); // true
test.myName(); // myName
const obj = {};
obj.__proto__ = Test.prototype;
obj.myName(); // myName
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-object.prototype.__proto__ |


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

# Original Wiki contributors
longlho
fscholz
wbamberg
arai
nmve
Sebastianz
eduardoboucas


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


Temporal.Now.timeZoneId()

Temporal.Now.timeZoneId()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
The Temporal.Now.timeZoneId()
static method returns a time zone identifier representing the system's current time zone. Most systems will return a primary time zone identifier such as "America/New_York"
, though offset time zone identifier such as "-04:00"
is possible too. The time zone identifier returned is the default time zone used by the other Temporal.Now
methods.
Syntax
Temporal.Now.timeZoneId()
Parameters
None.
Return value
A valid time zone identifier representing the system's current time zone. The returned time zone identifier is never a non-primary time zone identifier (alias). For example, it would always return "Asia/Kolkata"
(new name) instead of "Asia/Calcutta"
(old name). For more information, see time zones and offsets.
If the implementation does not support time zones, the method always returns "UTC"
.
Examples
Getting the system's current time zone
console.log(Temporal.Now.timeZoneId()); // e.g.: "America/New_York"
Specifications
| Specification |
|---|
| Temporal # sec-temporal.now.timezoneid |


Symbol.prototype.description

Symbol.prototype.description
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.
The description
accessor property of Symbol
values returns a string containing the description of this symbol, or undefined
if the symbol has no description.
Try it
console.log(Symbol("desc").description);
// Expected output: "desc"
console.log(Symbol.iterator.description);
// Expected output: "Symbol.iterator"
console.log(Symbol.for("foo").description);
// Expected output: "foo"
console.log(`${Symbol("foo").description}bar`);
// Expected output: "foobar"
Description
Symbol
objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The Symbol.prototype.description
property can be used to read that description. It is different to Symbol.prototype.toString()
as it does not contain the enclosing "Symbol()"
string. See the examples.
Examples
Using description
js
Symbol("desc").toString(); // "Symbol(desc)"
Symbol("desc").description; // "desc"
Symbol("").description; // ""
Symbol().description; // undefined
// well-known symbols
Symbol.iterator.toString(); // "Symbol(Symbol.iterator)"
Symbol.iterator.description; // "Symbol.iterator"
// global symbols
Symbol.for("foo").toString(); // "Symbol(foo)"
Symbol.for("foo").description; // "foo"
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-symbol.prototype.description |


Temporal.Now.instant()

Temporal.Now.instant()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
The Temporal.Now.instant()
static method returns the current time as a Temporal.Instant
object.
Syntax
js
Temporal.Now.instant()
Parameters
None.
Return value
A Temporal.Instant
object representing the current time, with potentially reduced precision.
Examples
Measuring time elapsed
The following example measures two instants in time and calculates the duration between them, and gets the total duration in milliseconds:
js
const start = Temporal.Now.instant();
// Do something that takes time
const end = Temporal.Now.instant();
const duration = end.since(start);
console.log(duration.total("milliseconds"));
Specifications
| Specification |
|---|
| Temporal # sec-temporal.now.instant |


Temporal.Duration.prototype.weeks

Temporal.Duration.prototype.weeks
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
The weeks
accessor property of Temporal.Duration
instances returns an integer representing the number of weeks 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 weeks, the weeks
absolute value's range depends on the calendar (how many weeks are in a month or year).
The set accessor of weeks
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 weeks
js
const d1 = Temporal.Duration.from({ weeks: 1, days: 1 });
const d2 = Temporal.Duration.from({ weeks: -1, days: -1 });
const d3 = Temporal.Duration.from({ weeks: 1 });
const d4 = Temporal.Duration.from({ days: 7 });
console.log(d1.weeks); // 1
console.log(d2.weeks); // -1
console.log(d3.weeks); // 1
console.log(d4.weeks); // 0
// Balance d4
const d4Balanced = d4.round({
largestUnit: "weeks",
relativeTo: Temporal.PlainDate.from("2021-01-01"), // ISO 8601 calendar
});
console.log(d4Balanced.weeks); // 1
console.log(d4Balanced.days); // 0
Specifications
| Specification |
|---|
| Temporal # sec-get-temporal.duration.prototype.weeks |
Browser compatibility
See also
Temporal.Duration
Temporal.Duration.prototype.years
Temporal.Duration.prototype.months
Temporal.Duration.prototype.days
Temporal.Duration.prototype.hours
Temporal.Duration.prototype.minutes
Temporal.Duration.prototype.seconds
Temporal.Duration.prototype.milliseconds
Temporal.Duration.prototype.microseconds
Temporal.Duration.prototype.nanoseconds


Symbol.toPrimitive

Symbol.toPrimitive
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2017.
The Symbol.toPrimitive
static data property represents the well-known symbol Symbol.toPrimitive
. All type coercion algorithms look up this symbol on objects for the method that accepts a preferred type and returns a primitive representation of the object, before falling back to using the object's valueOf()
and toString()
methods.
Try it
const object = {
[Symbol.toPrimitive](hint) {
if (hint === "number") {
return 42;
}
return null;
},
};
console.log(+object);
// Expected output: 42
Value
The well-known symbol Symbol.toPrimitive
.
Property attributes of Symbol.toPrimitive | |
|---|---|
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
With the help of the Symbol.toPrimitive
property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument hint
, which specifies the preferred type of the result primitive value. The hint
argument can be one of "number"
, "string"
, and "default"
.
The "number"
hint is used by numeric coercion algorithms. The "string"
hint is used by the string coercion algorithm. The "default"
hint is used by the primitive coercion algorithm. The hint
only acts as a weak signal of preference, and the implementation is free to ignore it (as Symbol.prototype[Symbol.toPrimitive]()
does). The language does not enforce alignment between the hint
and the result type, although [Symbol.toPrimitive]()
must return a primitive, or a TypeError
is thrown.
Objects without the [Symbol.toPrimitive]
property are converted to primitives by calling the valueOf()
and toString()
methods in different orders, which is explained in more detail in the type coercion section. [Symbol.toPrimitive]()
allows full control over the primitive conversion process. For example, Date.prototype[Symbol.toPrimitive]()
treats "default"
as if it's "string"
and calls toString()
instead of valueOf()
. Symbol.prototype[Symbol.toPrimitive]()
ignores the hint and always returns a symbol, which means even in string contexts, Symbol.prototype.toString()
won't be called, and Symbol
objects must always be explicitly converted to strings through String()
.
Examples
Modifying primitive values converted from an object
Following example describes how Symbol.toPrimitive
property can modify the primitive value converted from an object.
// An object without Symbol.toPrimitive property.
const obj1 = {};
console.log(+obj1); // NaN
console.log(`${obj1}`); // "[object Object]"
console.log(obj1 + ""); // "[object Object]"
// An object with Symbol.toPrimitive property.
const obj2 = {
[Symbol.toPrimitive](hint) {
if (hint === "number") {
return 10;
}
if (hint === "string") {
return "hello";
}
return true;
},
};
console.log(+obj2); // 10 — hint is "number"
console.log(`${obj2}`); // "hello" — hint is "string"
console.log(obj2 + ""); // "true" — hint is "default"
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-symbol.toprimitive |


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


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

# Original Wiki contributors
mfuji09
fscholz
rwaldron
alattalatta
wbamberg
doubleOrt
weblzf
jameshkramer
imagineer-aman
Mingun
AlexChao
Sheppy
ethertank
evilpie
Sevenspade
Mgjbot
Ptak82


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

# Original Wiki contributors
stockiNail
nuragic
mfuji09
wwahammy
fscholz
wbamberg
sideshowbarker
alexrussell


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

# Original Wiki contributors
mpcsh
romulocintra


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

# Original Wiki contributors
mfuji09
chrisbruford
wbamberg
fscholz
sideshowbarker
mika76
leothorp
SphinxKnight
Robg1
schalkneethling
jameshkramer
thetalecrafter
eduardoboucas
Mingun
Norbert
Sheppy
ethertank
evilpie
pwalton
Dikrib
Bold
Ptak82
Maian
Dria