Problem Statement
What is the result of 10 + '5' in JavaScript?
Explanation
The result is the string 105 because of type coercion.
When the plus operator is used with a string and a number, JavaScript converts the number to a string and performs concatenation instead of addition.
The number 10 becomes the string 10, then concatenates with the string 5 to produce 105.
Key rule to remember:
The plus operator with any string performs string concatenation. Other arithmetic operators like minus, multiply, and divide perform numeric conversion.
This is a common source of bugs, so always be careful when using plus with mixed types.
Code Solution
SolutionRead Only
console.log(10 + '5'); // '105' (string concatenation)
console.log(10 - '5'); // 5 (numeric subtraction)
console.log(10 * '5'); // 50 (numeric multiplication)
console.log('10' / '5'); // 2 (numeric division)
// Force numeric addition
console.log(10 + Number('5')); // 15
console.log(10 + (+'5')); // 15 (unary plus)
// Multiple operations
console.log(10 + 5 + '5'); // '155' (15 + '5')
console.log('5' + 10 + 5); // '5105' (all strings)