String Concatenation Instead of Addition
Quick summary
You used + with a string and a number, so JavaScript concatenated them (e.g., "10" + 5 = "105") instead of adding.
Why this happens
One operand is a string, causing + to concatenate instead of add
User input (which is always a string) was not converted to a number
JSON or form data returned strings instead of numbers
Minimal example
let a = "10";
let b = 5;
console.log(a + b); // "105" — concatenation!let a = "10";
let b = 5;
console.log(Number(a) + b); // 15 — additionWhen one operand is a string, + concatenates. "10" + 5 gives "105". Converting a to a number with Number() makes + perform addition: 10 + 5 = 15.
How to diagnose
Check the types of both operands with typeof
Look for quotes around values that should be numbers
Print the result to see if it is a string instead of a number
How to fix
Convert strings to numbers with Number(), parseInt(), or the unary +
Use template literals for intentional string concatenation
Validate and convert user input before arithmetic
How to prevent
Always convert user input to numbers before arithmetic
Use TypeScript to enforce numeric types
Related Resources
Related Lessons
- Data Types
Learn about type coercion.