Shankar Cabus
Shankar Cabus

Reputation: 9792

JavaScript concating with number as string

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

Upvotes: 2

Views: 1569

Answers (4)

raina77ow
raina77ow

Reputation: 106483

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

Upvotes: 4

Easwar Raju
Easwar Raju

Reputation: 273

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

Upvotes: 0

vivek_nk
vivek_nk

Reputation: 1600

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

Upvotes: 0

Bill the Lizard
Bill the Lizard

Reputation: 406115

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

Upvotes: 2

Related Questions