+ 9
JavaScript String Manager
Why in JavaScript "11" + 1 = "111" And "11" - 1 = 10
15 Answers
+ 9
"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[0] = 10;
console.log(a+1); // result 101
let b = [];
b[0] = 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
+ 5
"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...
+ 4
you've made a little fault, its:
"11" + 1 = "111"
"11" - 1 = 10
+ 4
+ 4
Qudusayo probably to avoid runtime errors and also to shorten code đ€·ââïž
+ 3
Qudusayo it's just the way JavaScript handles such operations. đ€·ââïž
+ 3
if there's string data type,
then + operator in javascript is to concat string and the closest number data type.
+ 1
The simplest and often used way to cast a number to a string is by using the + operator.
14 + "" // "14"
Whenever you are using â+â or â-â the values that you are adding or subtracting must be of the same type. Now in the above example they obviously are not. So what will happen is that JS will try to even them outâââin this case cast our number to a string and then add them together. In other words every â+â expression that involves a string will result in a string.
42 + "0" // "420"
We can concat strings using â+â, but what will happen if we use â-â? It can be used only on numbers, so once again, JS will cast the values to be of the same typeâââthis time numbers.
"42" - 7 // 35
"42" - 0 // 42
"42" - "9" // 33
Okay thatâs not that hard, but there is always a catch. Letâs try adding two arrays together and see what happens:
["alex", "sam"] + ["jon", "mary"] // "alex,samjon,mary"
Wait, what just happened? Now, whenever you use the â+â operator, the values will concatenate if one is already a string or they