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.
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.
- 2 mathsisfun./positive-negative-integers.html – Thom-x Commented Jul 23, 2015 at 20:53
- 3 Well, you are subtracting a negative number. – John Weisz Commented Jul 23, 2015 at 20:54
5 Answers
Reset to default 10Makes perfect sense, a double negative in mathematics will always evaluate to a positive
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)
It is interpreting 1 - - 1
as 1 - -1
which equals 2.
If you think about it, "- -1" equals to "+1", so "1 - - 1" equals to "1 + 1" which equals two.
In math -- = +
. If I take 1 - (-1)
I get 2
. Subtracting a negative number is the same as adding the number...