I was writing some JavaScript tests in Jest just to practice. I wrote the following function:
const divide = (a, b) => {
if (isNaN(a) || isNaN(b)) {
throw new Error("This function expect 2 numbers");
}
return a / b;
};
Then I wrote the following test:
describe("Test divide operator", () => {
it("Check the divide function", () => {
expect(divide(10, 0)).toBe(Infinity);
expect(divide(0, 0)).toBe(NaN);
expect(divide(Infinity, Infinity)).toBe(NaN);
expect(divide(10, Infinity)).toBe(0);
expect(divide(10, -Infinity)).toBe(0); // THIS TEST FAILS
});
});
I received the following error:
expect(received).toBe(expected) // Object.is equality
Expected: 0
Received: -0
Is it a JavaScript bug? Anyone knows why 0 can be negative in JavaScript? In my opinion, it is a little awkward to have to write "-0" just to pass the test.
Thanks.
This is not a bug it is a "feature" from IEEE-754 about floating point arithmetic. -0
is a signed 0 and javascript implements it correctly.
It's extremely rare to actually encounter and controversial as well. Other languages handle it differently.
Also -0 === 0 AND -0 === +0
so it normaly does not matter.