See, Math.pow(x, -n)
is really the same as 1/Math.pow(x, n)
. You're quite correct in noticing that odd power of a negative number is a negative. And when you do 1/negative
, it's still negative
, obviously.
But I guess the key part of the question is this:
while -0 is indeed a number if you open your mind, it's not a negative one.
Well, in JavaScript it's actually treated as a negative value in many aspects - apart from direct comparison with 0, of course. For example, Math.abs(-0)
returns 0
, not -0
, and modulo operations save the sign:
0 % 42; // 0
-0 % 42; // -0
One trick stands out of the crowd, however: if you divide any positive number by 0
, you'll get Infinity
:
console.log(1/0); // Infinity
console.log(Number.MIN_VALUE/0); // still Infinity
... but if you divide the same number by -0
, guess what, you'll get -Infinity
:
console.log(Number.MIN_VALUE/-0); // -Infinity
This trick is commonly used when you just have to discern between 0
and -0
- as direct comparison (0 === -0
) evaluates to true
.
Now, why a language has to have an evil twin negative counterpart of a normal zero? As @Barmar said, the consistency is (most probably) the key reason here. For example, there's a well known rule in JS: when you do modulo operation, the sign of result is the sign of the first operand. So both this -5 % 2
and -5 % -2
result it -1
, while both 5 % 2
and 5 % -2
result in 1
.
It was a bit surprising for me when I discovered that, but the same rule applies when the first operand is actually divisible by the second one:
5 % 5; // 0
-5 % 5; // -0
-5 % -5; // -0
5 % -5; // 0
... so the rule's still intact. Even more important reason, however, is ability to reverse the operation consistently: if a / b => c
, then a / c
should be equal to b
. In JS, it's true even when b
is Infinity
or -Infinity
, as you get different c
(0
in the former, -0
in the latter) and will be able to 'restore' the divisor.