Question

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

Was it helpful?

Solution

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. )

OTHER TIPS

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.)

"-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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top