The following code gives weird results:
console.log("" + 1 + 10 + 2 - 5 + "8");
I've tried inputting various different values to work it out but I cannot understand what's going on under the hood.
If you add a number and a string, the result will be a string!
In JavaScript, the + operator is used for both numeric addition and string concatenation. When you "add" a number to a string the interpreter converts your number to a string and concatenates both together.
It happens because adding int and String gives you a new String. That means if you have int x = 5 , just define x + "" and you'll get your new String.
In javascript, we can also concatenate strings with variables. We can do more than concatenate strings in Javascript: we can concatenate integers and booleans to strings.
"" + 1 === "1" "1" + 10 === "110" "110" + 2 === "1102" "1102" - 5 === 1097 1097 + "8" === "10978"
In JavaScript, the +
operator is used for both numeric addition and string concatenation. When you "add" a number to a string the interpreter converts your number to a string and concatenates both together.
When you use the -
operator, however, the string is converted back into a number so that numeric subtraction may occur.
When you then "add" a string "8"
, string concatenation occurs again. The number 1097
is converted into the string "1097"
, and then joined with "8"
.
string + number = concatenated string
number + number = the sum of both numbers
string - number = the difference between (coerced string) and the number
If one or both operands is string, then the plus is considered as string concatenation operator rather than adding numbers.
the minus operator always try to convert both operands to numbers.
so:
"" + 1 + 10 + 2 = (string) "1102" "1102" - 5 = (number) 1097 1097 + "8" = (string) "10798"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With