Hiprup

What is the output of '5' + 3 and '5' - 3?

The operator decides which way coercion goes.

  • '5' + 3 — + with a string concatenates, so 3 becomes "3" → "53" (a string).

  • '5' - 3 — - has no string meaning, so '5' becomes the number 5 → 2 (a number).

Rule: + prefers strings; -, *, / always coerce to numbers.

console.log('5' + 3);    // '53' (string concatenation)
console.log('5' - 3);    // 2 (numeric subtraction)
console.log('5' * 3);    // 15 (numeric)
console.log('5' / 3);    // 1.666... (numeric)
console.log('5' % 3);    // 2 (numeric)

// + is the only operator that concatenates
console.log('5' + 3);    // '53' (concat)
console.log(5 + '3');    // '53' (concat)
console.log(5 + 3);      // 8 (addition)

// Force numeric with unary +
console.log(+'5' + 3);   // 8 (number + number)

// Multiple + with mixed types
console.log(1 + 2 + '3');  // '33' (1+2=3, 3+'3'='33')
console.log('1' + 2 + 3);  // '123' ('1'+2='12', '12'+3='123')
  • with a string = concatenation (string wins). -, *, /, % = always numeric (convert strings to numbers). Evaluation is left-to-right: 1+2+'3' = (1+2)+'3' = 3+'3' = '33'. '1'+2+3 = ('1'+2)+3 = '12'+3 = '123'. Unary + forces numeric conversion.
  • is the only operator that concatenates. -, *, /, % always do math. The left-to-right evaluation (1+2+'3' = '33' vs '1'+2+3 = '123') is the follow-up question. Unary + for forcing numeric conversion.
What is the output of '5' + 3 and '5' - 3? | Hiprup