JavaScript Symbol toPrimitive Property
Last Updated :
19 May, 2023
In Javascript, by the use of the Symbol.toPrimitive Property (used as a function value), one can convert an object to its corresponding primitive value.To call the function , a string argument called hint is passed. The hint argument specifies the preferred return type of the resultant primitive value. The hint argument can take “number”, “string”, and “default” as its values.
Example:
Javascript
function myFunction() {
const obj2 = {
[Symbol.toPrimitive](hint) {
if (hint === 'number' ) {
return 0;
}
if (hint == 'string' ) {
return 'String' ;
}
if (hint == 'default' ) {
return 'Default' ;
}
}
};
console.log(+obj2);
console.log(`${obj2}`);
console.log(obj2 + '' );
}
myFunction();
|
Output:
0
String
Default
Explanation: In the above example, depending upon the type of hint passed in the arguments, we obtain the desired output.
We have a complete list of Javascript Symbols methods, to check those please go through this JavaScript Symbol Complete Reference article.
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...