UNB/ CS/ David Bremner/ teaching/ cs2613/ books/ mdn/ Reference/ Global Objects/ Date/ Date.prototype[@@toPrimitive]()

The [@@toPrimitive]() method of Date instances returns a primitive value representing this date. It may either be a string or a number, depending on the hint given.

Syntax

date[Symbol.toPrimitive](hint)

Parameters

Return value

If hint is "string" or "default", this method returns a string by coercing the this value to a string (first trying toString() then trying valueOf()).

If hint is "number", this method returns a number by coercing the this value to a number (first trying valueOf() then trying toString()).

Exceptions

Description

The [@@toPrimitive]() method is part of the type coercion protocol. JavaScript always calls the [@@toPrimitive]() method in priority to convert an object to a primitive value. You rarely need to invoke the [@@toPrimitive]() method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.

The [@@toPrimitive]() method of the Date object returns a primitive value by either invoking this.valueOf() and returning a number, or invoking this.toString() and returning a string. It exists to override the default primitive coercion process to return a string instead of a number, because primitive coercion, by default, calls valueOf() before toString(). With the custom [@@toPrimitive](), new Date(0) + 1 returns "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)1" (a string) instead of 1 (a number).

Examples

Using [@@toPrimitive]()

const d = new Date(0); // 1970-01-01T00:00:00.000Z

d[Symbol.toPrimitive]("string"); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"
d[Symbol.toPrimitive]("number"); // 0
d[Symbol.toPrimitive]("default"); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"

Specifications

Browser compatibility

See also