Does the addition operator before char in javascript convert them to number?
1 + + "1" === 2;
+"1" + + "1" === 2;
"1" + "1" === "11"
Earlier question doesn't explain why it's happening only tells us various ways of converting strings to number and vice versa.
1 + + "1" === 2;
Unary operator +
has higher precedence, so +"1"
will be evaluated first, converting "1"
into integer of value of 1, so it will become
1+1 === 2
The second line
+"1" + + "1" === 2;
This is similar. Unary operator +
has higher precedence, so both +"1"
will be evaluate to positive integer value of 1.
"1" + "1" === "11"
Because in JavaScript +
is also string concatenation operator if both operands are string, this will concat both strings.
More information https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators
Update: @torazaburo is correct.
The evaluation of +"1"
in code here has nothing to do with operator precedence.
String concatenation will happen if either operand is string.
In JS there is implicit type coercion. For instance, the binary plus operator coerces a number into string if the other operand is a string. "1" + 2 === "12"
or 3 + "4" === "34"
.
However when used with a single operand it works backwards and +"1"
coerces the "1"
string to a number 1
. Just like parseInt("1")
.
So +"1" + 3 === 4
What you are looking for is the unary plus. Lets analyze the first 2 cases:
The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already.
+ "1"
part is converting the string "1"
to a number 1
. The number 1 is then added to the other number 1 resulting in 2 === 2
Same as above, but instead there are 2 unary operation now. So both string "1"
are converted to number 1 resulting in 2 === 2
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