+ 9
JavaScript String Manager
Why in JavaScript "11" + 1 = "111" And "11" - 1 = 10
15 odpowiedzi
+ 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
Anton Böhler No
+ 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