Skip to content

JavaScript Function Issue #606

Answered by NitishKumar525
Sachin2815 asked this question in Q&A
Discussion options

You must be logged in to vote

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:

function calculateSum(a, b) {
    let result = Number(a) + Number(b);
    return result;
}

console.log(calculateSum(5, '10')); // Output: 15

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by Sachin2815
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants