JS Built-ins
TypeCoercionintermediate

Addition Operator Coercion

Addition Operator (+ ) Coercion

The + operator has dual behavior:

  • Addition: if both operands are numbers, add numerically
  • Concatenation: if either operand is a string, convert both to strings and concatenate

Examples:

  • 1 + '2' is '12' (string concatenation, not addition)
  • 1 + 2 + '3' is '33' (left-to-right: 1+2=3, then 3+'3'='33')
  • '1' + 2 + 3 is '123' (left-to-right: '1'+2='12', then '12'+3='123')

Challenge: Demonstrate the order of operations with + operator.

πŸ’‘ Hints (4)
  • β€’ If either operand is a string, the result is concatenation (string).
  • β€’ Operations are evaluated left-to-right.
  • β€’ 1 + 2 = 3 (both numbers), then 3 + "3" = "33" (concatenation).
  • β€’ "1" + 2 = "12" (concatenation), then "12" + 3 = "123" (concatenation).