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

Object to primitive coercion

πŸ’‘

Hint

valueOf() is preferred for arithmetic. toString() for string contexts. You can customize both.

What does this output?

const obj = {
  valueOf() { return 42; },
  toString() { return 'hello'; }
};

console.log(obj + 1);
console.log(`${obj}`);
console.log(obj * 2);

Correct Output

43
hello
84

Why this output?

Explanation: For + with number, valueOf() is preferred β†’ 42+1=43. Template literals prefer toString() β†’ "hello". Arithmetic (*) forces numeric: valueOf() β†’ 42*2=84.

Key Insight: valueOf() is preferred for arithmetic. toString() for string contexts. You can customize both.

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