Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negatives in underscore.js: why is _isEqual(0, -1 * 0) returning false?

Using the javascript library underscore.js (v.1.3.1), I've reproduced the following on the mac in up-to-date Chrome (17.0.963.56) and in Firefox 7.0:

0 === -1 * 0
> true

_.isEqual(0, -1 * 0)
> false

This is surprising, at least to me. I expected that two values for which === is true would result in _.isEqual also being true.

What's going on here? Thanks!

like image 595
brahn Avatar asked Jan 17 '23 09:01

brahn


2 Answers

It has been put explicitly in the source:

function eq(a, b, stack) {
  // Identical objects are equal. `0 === -0`, but they aren't identical.
  // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
  if (a === b) return a !== 0 || 1 / a == 1 / b;

In fact, JavaScript does interpret 0 and -0 differently, but you usually don't see this because 0 == -0 and 0 === -0. There are only a few ways to check for the difference.

like image 55
pimvdb Avatar answered Jan 31 '23 09:01

pimvdb


Look at the source for the eq function here. -1 * 0 is -0, not 0, so 0 and -0 aren't equal, according to isEqual.

Relevant line:

// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
if (a === b) return a !== 0 || 1 / a == 1 / b;

I did know about this before, but it'll make for some interesting evil code.

like image 35
Ry- Avatar answered Jan 31 '23 07:01

Ry-