2

Why does x = "1"- -"1" work and set the value of x to 2?

Why doesn't x = "1"--"1" works?

enter image description here

4 Answers 4

4

This expression...

"1"- -"1"

... is processed as ...

"1"- (-"1")

... that is, substract result of unary minus operation applied to "1" from "1". Now, both unary and binary minus operations make sense to be applied for Numbers only - so JS converts its operands to Numbers first. So that'll essentially becomes:

Number("1") - (-(Number("1"))

... that'll eventually becomes evaluated to 2, as Number("1"), as you probably expect, evaluates to 1.


When trying to understand "1"--"1" expression, JS parser attempts to consume as many characters as possible. That's why this expression "1"-- is processed first.

But it makes no sense, as auto-increment/decrement operations are not defined for literals. Both ++ and -- (both in postfix and prefix forms) should change the value of some assignable ('left-value') expression - variable name, object property etc.

In this case, however, there's nothing to change: "1" literal is always "1". )


Actually, I got a bit different errors (for x = "1"--"1") both in Firefox:

SyntaxError: invalid decrement operand

... and Chrome Canary:

ReferenceError: Invalid left-hand side expression in postfix operation

And I think these messages actually show the reason of that error quite clearly. )

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

Comments

2

Because -- is an operator in JavaScript.

When you separate the - characters in the first expression, it's unambiguous what you mean. When you put them together, JavaScript interprets them as one operator, and the following "1" as an unexpected string. (Or maybe it's the preceding "1"? I'm honestly not sure.)

3 Comments

Actually, it's still unambiguous for JS even with "1"--"1" - that's always treated as ("1"--)"1". So yes, if "1"-- expression were valid, "1" should have been treated as unexpected string. )
@raina77ow "1"--"1" is unambiguous to JavaScript, but I can interpret it in two different ways. The way that the OP meant, and the way JavaScript interprets it.
0

"-1" = -1 (unary minus converts it to int) So. "1" - (-1) now, "+" is thje concatenation operator. not -. so JS returns the result 2 (instead of string concat).

also, "1"--"1" => here "--" is the decrement operator, for which the syntax is wrong as strings will not get converted automatically in this case.

Comments

0

because -- is an operator for decrement and cannot be applied on constant values.

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.