The Javascript date.@@toPrimitive() function is an inbuilt function in JavaScript that is used to convert the date object into a primitive value. A number or string is known as a primitive value.
Syntax:
Dateobj[Symbol.toPrimitive](hint);
Parameter: This function accepts a single parameter. Depending on the argument, the method can return either a string or a number.
Return Values: It returns the primitive value of the given date object.
The below examples illustrate the @@toPrimitive() function in JavaScript.
Example 1: When a hint is the default, [@@toPrimitive]() tries to call the toString method, and if the toString method does not exist it tries to call the valueOf method.
javascript
<script> // Here a date has been assigned // while creating Date object var dateobj = new Date(); // converting the date object to a primitive value var result = dateobj[Symbol.toPrimitive]( "default" ) // Printing year console.log(result); </script> |
Output:
Thu Sep 27 2018 12:49:02 GMT+0530 (India Standard Time)
Example 2: When a hint is a number, [@@toPrimitive]() tries to call the valueOf method and if the valueOf method does not exist, it calls the toString method.
javascript
<script> // Here a date has been assigned // while creating Date object var dateobj = new Date(); // converting the date object to a primitive value var result = dateobj[Symbol.toPrimitive]( "number" ) // Printing year console.log(result); </script> |
Output:
1538032776898
Example 3: When a hint is a string, [@@toPrimitive]() tries to call the toString method, and if the toString method does not exist it tries to call the valueOf method.
javascript
<script> // Here a date has been assigned // while creating Date object var dateobj = new Date(); // converting the date object to a primitive value var result = dateobj[Symbol.toPrimitive]( "string" ) // Printing year console.log(result); </script> |
Output:
Thu Sep 27 2018 12:50:04 GMT+0530 (India Standard Time)
Note: Output may vary as per the current date and time.
Errors and Exceptions: When a hint is anything other than “string”, “default” or”number”, [@@toPrimitive]() tries to call the toString method and if the toString method does not exist it tries to call the valueOf method, and if valueOf method is also not applicable then [@@toPrimitive]() throws a TypeError.
Example:
javascript
<script> // Here a date has been assigned // while creating Date object var dateobj = new Date(); // converting the date object to a primitive value var result = dateobj[Symbol.toPrimitive](90) // Printing year console.log(result); </script> |
Output:
TypeError: Symbol.toPrimitive: expected "string", "number", or "default", got number