🖥️FE🖥️

[JS] string * string , string + string. type coercion rules.

들눈 2023. 4. 14. 17:51

It sounds like you may be concatenating the integers as strings instead of adding and multiplying them as numeric values. In JavaScript, the + operator can be used for both string concatenation and addition, depending on the context in which it is used.

Here's an example:

console.log(10 + 30); // Output: 40
console.log("10" + "30"); // Output: "1030"
console.log(10 * 30); // Output: 300
console.log("10" * "30"); // Output: 300

In the first example, 10 and 30 are added as numeric values, resulting in the expected answer of 40.
In the second example, "10" and "30" are concatenated as strings, resulting in the output of "1030".
Similarly, in the third example, 10 and 30 are multiplied as numeric values, resulting in the expected answer of 300.
In the fourth example, "10" and "30" are coerced to numeric values using the JavaScript type coercion rules, and then multiplied as numeric values, resulting in the output of 300.

Therefore, if you want to add or multiply two numbers in JavaScript, make sure that you are using the + or * operators with numeric values, not with strings.