Negative values ​​in underscore.js: why _isEqual (0, -1 * 0) returns false?

Using the javascript underscore.js library (v.1.3.1), I reproduced the following on 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 amazing, at least for me. I expected that two values ​​for which === true would cause _.isEqual to be true as well.

What's going on here? Thanks!

+4
source share
3 answers

The source file explicitly states :

 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; 

JavaScript actually interprets 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 the difference.

+4
source

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

Corresponding 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 knew about this before, but it will make some interesting evil code.

+3
source

It is deeper than that. JavaScript uses IEEE double-precision floating-point numbers, and they have different representations for 0 and -0 (which can be important when dealing with restrictions, etc.). But usually you don’t notice it, because 0 === -0.

+2
source

Source: https://habr.com/ru/post/1398478/


All Articles