+8

# JavaScript String Manager

Why in JavaScript "11" + 1 = "111" And "11" - 1 = 10

+7

"11"- 1 = 10 JavaScript sees that "11" is a string and it sees something is being subtracted from it. It says to itself, “Huh. Something is being subtracted from a string. Does that make sense to me? What do I do when something’s subtracted from a string?” It doesn’t have a rule for that! So it says, “Well, that second argument, the 1, is a number. What if I turn the first argument, the "11", into a number. Can I do that?” It turns out that, yes, it can turn the string "11"into a number. So then it asks, “Does subtracting one number from another make sense? Do I have a rule for subtracting one number from another?” It turns out that, yes, it does know how to subtract one number from another. So it converts the string, "11", to the number, 11, subtracts 1 from it, and displays the result, 10.

+5

Use parseInt(string).

+5

Filipe Cláudio I don't ask how to solve but I asked why I know JavaScript

+5

let a = []; a = 10; console.log(a+1); // result 101 let b = []; b = 10; console.log(parseInt(b)+1) // result 11

+5

Ok sorry, I just wanted to help

+5

Anton Böhler There Must be a reason

+5

It takes place due to coercion... In first case the number 1 is coerced to string and hence displayed as 111 Meanwhile the subtraction operator coerces the 11 to number so 10 https://hackernoon.com/understanding-js-coercion-ff5684475bfc

+4

you've made a little fault, its: "11" + 1 = "111" "11" - 1 = 10

+4

Anton Böhler No

+4

Qudusayo probably to avoid runtime errors and also to shorten code 🤷‍♂️

+4

"11"+1 will convert 1 to string to be "111" "11"-1 will convert 11 to number to be 10 And with mult and div same sub...

+3

Qudusayo it's just the way JavaScript handles such operations. 🤷‍♂️

+3