What is the output of the following code? const obj = {}; obj[Symbol.toPrimitive] = (hint) => hint === ‘number’ ? 42 : ‘hello’; console.log(+obj, `${obj}`, obj + ”);

JavaScript Professional Hard

JavaScript Professional — Hard

What is the output of the following code? const obj = {}; obj[Symbol.toPrimitive] = (hint) => hint === ‘number’ ? 42 : ‘hello’; console.log(+obj, `${obj}`, obj + ”);

Key points

  • Symbol.toPrimitive method defines object conversion
  • +obj coerces object to a number
  • `${obj}` coerces object to a string
  • The defined method returns different values based on the hint

Ready to go further?

Related questions