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}`);

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.

Further reading

Problem with a question

JavaScript · Senior · question 45

Test yourself

Take the JavaScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz