Learning Objectives
By the end of this lesson you will be able to:
- Explain what implicit type conversion (type coercion) is and why it exists
- List the most dangerous coercion behaviors in JavaScript, Python, and PHP
- Select the input values that specifically target coercion bugs
What is Type Coercion?
Type coercion is when a programming language automatically converts a value from one type to another without explicit instruction from the programmer.
In strongly typed languages (Java, C#), you generally can't add a string to a number without explicit conversion. The compiler rejects it.
In dynamically typed languages (JavaScript, PHP, Python 2), the language tries to "figure out what you meant" and convert automatically. This convenience is also a source of bugs.
Classic Coercion Bugs
JavaScript: + is ambiguous
"5" + 5 = "55" // String + Number → String concatenation
5 + "5" = "55" // Number + String → String concatenation
5 + 5 + "5" = "105" // Evaluated left to right: 10 + "5" → "105"
"5" - 5 = 0 // String - Number → 0 (subtraction coerces to number)
"5" * 5 = 25 // String * Number → 25 (multiplication coerces to number)
JavaScript: Loose equality
"0" == false // true (both coerce to 0)
"" == false // true
null == undefined // true (special case)
0 == "" // true
PHP (notorious)
"1" + "2" = 3 // Different from JavaScript! PHP adds, doesn't concat
"1abc" + 2 = 3 // PHP parses the leading number and ignores "abc"
Where These Bugs Appear in Web Applications
-
Form input processing: User types "10" in a number field. Backend receives it as a string
"10". If code doesdiscount = price - "10", JavaScript/PHP may subtract; Python 3 will throw an error. -
API response processing: A REST API returns
{"price": "99.99"}(string). Backend code does arithmetic with it. -
Database results: Some database drivers return numeric columns as strings. Code that expects to do math on them gets string concatenation instead.
How to Detect Coercion Bugs
They show up as:
- Numerical fields concatenated instead of added:
$100+$50=$10050(wrong!) - Division producing string operations
- Boolean operations on numeric fields producing unexpected true/false results
Testing Strategy
- Input "numeric" values as quoted strings where possible
- Mix types in multi-field calculations
- Observe: does the result look concatenated rather than computed?
- Test with string-numeric inputs:
"5","5.0"," 5"(space before)
Pro Tip: If a discount calculator shows a price of $10050 when you apply a $50 discount to a $100 item, that's classic string concatenation from coercion. The discount was concatenated to the price string instead of subtracted from it.
Key Takeaways
- Type coercion converts values automatically in dynamically typed languages
- JavaScript
+does string concatenation if either operand is a string - Coercion bugs produce wrong results silently — no exception, just a wrong value
- Test with string-typed numeric inputs and observe whether arithmetic or concatenation occurs