Learning Objectives
By the end of this lesson you will be able to:
- Describe exactly why string + number equals concatenation in JavaScript and similar languages
- Identify the specific application scenarios where this bug commonly appears
- Create targeted test inputs that reliably trigger string-number coercion bugs
The Bug in Detail
In JavaScript (and to varying degrees in PHP, Ruby, and others), the + operator is overloaded:
- Number + Number: Addition (
5 + 5 = 10) - String + Anything: Concatenation (
"5" + 5 = "55","5" + true = "5true")
The ambiguity arises because form inputs, JSON responses, and URL parameters typically deliver data as strings. If the developer doesn't explicitly parse them to numbers before arithmetic, coercion happens.
Real Production Scenarios
Scenario 1: Discount Calculator
const price = req.body.price; // "100" (string from form)
const discount = req.body.discount; // "25" (string from form)
const final = price - discount; // 75 (works! subtraction coerces)
const final2 = price + discount; // "10025" (breaks! concatenation)
The developer tested subtraction (which works because - always coerces to number) but not other operators.
Scenario 2: Running Total
let total = 0;
items.forEach(item => {
total = total + item.price; // If item.price is a string, this concatenates!
// After 3 items: 0 + "5.99" = "05.99", then "05.99" + "12.99" = "05.9912.99"
});
Scenario 3: API Response Processing
An API returns {"amount": "100"} — amount as a string. Code does total += amount. This should add but instead concatenates.
The Inputs That Trigger This Bug
To test for string-number coercion bugs:
- String-formatted numbers: Submit
"100"(with quotes, if the API accepts JSON) - Numeric strings in form fields: All form fields submit as strings by default
- Mixed inputs: Submit one field as a number and one as a string
- Leading zeros:
"007"— some parsers strip the zeros, others don't
What the Bug Looks Like in the UI
- Price of $100 with a $25 discount shows $10025 instead of $75
- Running total shows
"012.9912.9915.99"instead of $41.97 - Percentage calculation shows
"100.5"instead of50.5
The common pattern: the result is too long (concatenated digits) rather than the expected arithmetic result.
Key Takeaways
"5" + 5 = "55"in JavaScript because+does string concatenation when a string is involved- Form fields always submit strings — developers must explicitly parse to numbers
- Subtraction, multiplication, division always coerce to number — only
+is ambiguous - Test by observing: is the result implausibly large (concatenated) or the correct arithmetic value?