JS Built-ins
TypeCoercionintermediate

Object to Primitive Coercion

Object to Primitive Coercion

Objects coerce to primitives via:

  1. valueOf() - returns primitive value if applicable
  2. toString() - returns string representation

Examples:

  • [] + [] is '' (both coerce to '', concatenate to '')
  • [] + {} is '[object Object]' ([] becomes '', {} becomes '[object Object]')
  • ({}) + [] is '[object Object]' (same, with explicit parentheses for clarity)

Challenge: Observe object-to-primitive coercion with the + operator.

πŸ’‘ Hints (4)
  • β€’ Arrays coerce to strings via toString(), which produces a comma-separated list of elements.
  • β€’ Empty arrays [] have no elements, so toString() returns an empty string.
  • β€’ Objects coerce to "[object Object]" by default.
  • β€’ When objects are used with +, they are first converted to primitives via toString(). If any operand converts to a string, + becomes concatenation β€” this is why [] + [] gives '' (both convert to empty string via toString()).