πŸ”΄ HardType CoercionπŸ’» Output Question

Symbol.toPrimitive custom coercion

πŸ’‘

Hint

Symbol.toPrimitive gives full control over all coercion paths. Hint is "number", "string", or "default". Overrides valueOf() and toString() when present.

What does this output?

const obj = {
  [Symbol.toPrimitive](hint) {
    if (hint === 'number') return 42;
    if (hint === 'string') return 'hello';
    return true; // default hint
  }
};

console.log(+obj);
console.log(`${obj}`);
console.log(obj + '');
console.log(obj == true);

Correct Output

42
hello
true
true

Why this output?

Explanation: +obj: numeric hint β†’ 42. Template literal: string hint β†’ "hello". obj + "": default hint β†’ true β†’ "true". obj == true: loose eq, default hint on both, obj β†’ true, true β†’ 1, 1 == 1 β†’ true.

Key Insight: Symbol.toPrimitive gives full control over all coercion paths. Hint is "number", "string", or "default". Overrides valueOf() and toString() when present.

More Type Coercion Output Questions

🟒 EasyLoose equality coercionβ†’πŸŸ‘ MediumAddition vs concatenationβ†’πŸŸ‘ MediumFalsy values comparisonβ†’πŸŸ‘ MediumNaN comparisonβ†’

Practice predicting output live β†’

66 output questions with instant feedback

πŸ’» Try Output Quiz