I accidentally typed the following JavaScript statement "1" + - "2"
and I have the result "1-2"
.
I am not sure why the minus sign was treated as a string rather than causing a syntax error.
I tried to search, but I did not get the answer I wanted.
Why the minus sign was treated as a string? it there online reference I can look at? thanks
Use the addition (+) operator, e.g. Number('1') + Number('2') . The addition operator will return the sum of the numbers.
JavaScript, like any good language, has the ability to join 2 (or more, of course) strings. How? We can use the + operator. I generally recommend the simplest route (which also happen to be the faster) which is using the + (or += ) operator.
Basic JavaScript Addition var x = 1; var y = 2; var result = x + y; The result is "3" in this simple example. Add numbers in JavaScript by placing a plus sign between them.
Simple: - "2"
evaluates to -2
because unary -
coerces its operand to a number, which is precisely the behavior defined in the ECMA-262 spec.
11.4.7 Unary
-
OperatorThe unary
-
operator converts its operand toNumber
type and then negates it. Note that negating+0
produces−0
, and negating−0
produces+0
.The production UnaryExpression
: -
UnaryExpression is evaluated as follows:
- Let expr be the result of evaluating UnaryExpression.
- Let oldValue be ToNumber(GetValue(expr)).
- If oldValue is NaN, return NaN.
- Return the result of negating oldValue; that is, compute a Number with the same magnitude but opposite sign.
Then it's just a matter of string concatenation: "1" + (-2)
evaluates, unsurprisingly, to "1-2"
. By this point it should comes as no surprise that the +
is a string concatenation (and not an addition) operator in the context because that's what the spec says.
Because, as always, that's the behavior required by the spec.
The original
"1" + - "2"
Is parsed as
"1" + ( - "2" )
The -
here converts the "2"
to a number and negates it, so - "2"
evaluates to -2
. So this becomes:
"1" + (-2)
Here, the +
causes the -2
to be converted to a string, "-2"
, and then does simple string concatenation.
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