JavaScript Function Issue #606
-
Description: function calculateSum(a, b) {
let result = a + b;
return result;
}
console.log(calculateSum(5, '10')); What is causing this issue, and how can I modify the function to ensure it returns the correct sum when given a number and a string? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
SolutionThe issue arises due to JavaScript's type coercion rules. When the To address this issue, you need to ensure that both parameters are treated as numbers before performing the addition. You can use the function calculateSum(a, b) {
let result = Number(a) + Number(b);
return result;
}
console.log(calculateSum(5, '10')); // Output: 15 |
Beta Was this translation helpful? Give feedback.
Solution
The issue arises due to JavaScript's type coercion rules. When the
+
operator is used with a number and a string, JavaScript converts the number to a string and performs string concatenation instead of numeric addition.To address this issue, you need to ensure that both parameters are treated as numbers before performing the addition. You can use the
Number
function to explicitly convert the string to a number: