Saturday, August 30, 2025
HomeLanguagesJavascriptJavaScript Symbol toPrimitive Property

JavaScript Symbol toPrimitive Property

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() {
      
    // Creation of an object with the
    // Symbol.toPrimitive property
    const obj2 = {
        [Symbol.toPrimitive](hint) {
  
            // If hint is number
            if (hint === 'number') {
                return 0;
            }
  
            // If the hint is string
            if (hint == 'string') {
                return 'String';
            }
  
            // If hint is default
            if (hint == 'default') {
                return 'Default';
                }
        }
    };
  
    // Hint passed is integer
    console.log(+obj2);
  
    // Hint passed is string
    console.log(`${obj2}`);
  
    // Hint passed is default
    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.  

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32249 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6617 POSTS0 COMMENTS
Nicole Veronica
11792 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11838 POSTS0 COMMENTS
Shaida Kate Naidoo
6731 POSTS0 COMMENTS
Ted Musemwa
7013 POSTS0 COMMENTS
Thapelo Manthata
6689 POSTS0 COMMENTS
Umr Jansen
6701 POSTS0 COMMENTS