Skip to content
Related Articles

Related Articles

Improve Article

JavaScript Symbol.toPrimitive Property

  • Last Updated : 23 Apr, 2021

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 it values.

Example:

HTML




<script>
    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();
</script>

Output:

In the above example, depending upon the type of hint passed in the arguments, we obtain the desired output.

My Personal Notes arrow_drop_up
Recommended Articles
Page :