18

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

1
  • 1
    Note that "1" + + "2" is also valid (returns "12"), but "1" ++ "2" is a syntax error because the ++ operator is not the same as two + operators in a row. And something silly like "1" + - + - "2" is valid too... Commented Nov 7, 2013 at 20:13

3 Answers 3

31

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 - Operator

The unary - operator converts its operand to Number type and then negates it. Note that negating +0 produces −0, and negating −0 produces +0.

The production UnaryExpression : - UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.
  2. Let oldValue be ToNumber(GetValue(expr)).
  3. If oldValue is NaN, return NaN.
  4. 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.


TL;DR

Because, as always, that's the behavior required by the spec.

Sign up to request clarification or add additional context in comments.

Comments

16

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.

Comments

0

Unary - operator (-x) has precedence over binary + operator (x + y).

So "1" + - "2" is actually parsed as "1" + -2, which in turn is parsed as a string concactenation "1" + "-2", to finally rsult in "1-2".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.