JavaScript · Senior · Question 45 of 75
What does the expression return?
const obj = {
[Symbol.toPrimitive](hint) {
return hint === "number" ? 42 : "obj";
},
};
console.log(+obj, `${obj}`);- ✓Correct answer:
42 obj - 2
NaN [object Object] - 3
42 42
Explanation
When converting to a primitive, the engine calls Symbol.toPrimitive with the hint 'number', 'string' or 'default'. Without it, valueOf and toString are used. This is how, for example, date subtraction works: date2 - date1.