denysdovhan / wtfjs

🤪 A list of funny and tricky JavaScript examples
http://bit.ly/wtfjavascript
Do What The F*ck You Want To Public License
34.95k stars 2.55k forks source link

A nice thing about zeroes in javascript #155

Closed Pflyg closed 3 years ago

Pflyg commented 4 years ago

This weird behavior with strict comparisons and signed zeroes:

var a = 0;
var b = -0;
(a === b); //true (0 === -0)
(1 / a) == (1 / b); //false (Infinity  == -Infinity)
pero5ar commented 4 years ago

Infinity == -Infinity does not surprise me because those are two different numbers on the extended real number line, so it's the same as doing 5 == -5.

The zero thing is neat. It's a thing defined by the standard for singed zero comparison. It makes sense in regards to that standard because the only difference between == and === should that === checks the type first and does not try to cast values, so values that are both numbers should get compared by value and not by notation (e.g. 1e1 === 10 is true).

That being said, I'm definitely in favour of adding the 0 === -0 example as that is a thing that people might get wrong about the === operator.