Vidul
Vidul

Reputation: 10528

How come "minus, space, minus" evaluates to the "plus" operator?

node -e 'console.log(- -1)' // prints 1 which makes sense

However:

node -e 'console.log(1 - - 1)' // prints 2 which does not make sense to me

integer - - integer magically converts "minus, space, minus" to the "plus" operator. Why?

Update: It seems I wasn't clear enough. The question is not why double negative in mathematics will always evaluate to a positive but how this magically evaluates to the + operator; these are two different scenarios - making a negative number positive is one thing, invoking implicitly the + is another thing.

Upvotes: 3

Views: 886

Answers (5)

brso05
brso05

Reputation: 13222

In math -- = +. If I take 1 - (-1) I get 2. Subtracting a negative number is the same as adding the number...

Upvotes: 0

asmockler
asmockler

Reputation: 187

It is interpreting 1 - - 1 as 1 - -1 which equals 2.

Upvotes: 1

dsh
dsh

Reputation: 12213

One of your - characters is a unary minus, or a negative sign. That makes one of your literals a "negative one". The other one is a subtraction.

1 - - 1

is the same as:

1 - (-1)

While

- - 1

is the same as

0 - (-1)

Upvotes: 4

Nathan
Nathan

Reputation: 1371

If you think about it, "- -1" equals to "+1", so "1 - - 1" equals to "1 + 1" which equals two.

Upvotes: 0

Darren H
Darren H

Reputation: 902

Makes perfect sense, a double negative in mathematics will always evaluate to a positive

Upvotes: 10

Related Questions