JavaScript Function Issue #606
Answered
by
NitishKumar525
Sachin2815
asked this question in
Q&A
|
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? |
Answered by
NitishKumar525
Sep 2, 2024
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 |
0 replies
Answer selected by
Sachin2815
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
Numberfunction to explicitly convert the string to a number: