Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash implementation of return value === 0 ? value : 0

Can anyone explain why this line is used in lodash library.

if (!value) {
    return value === 0 ? value : 0;
}

and why not just return 0;

like image 562
pokemon Avatar asked Jul 01 '16 20:07

pokemon


1 Answers

There are two different values which are considered strictly equal to zero: +0 and -0:

+0 === +0;
+0 === -0;
-0 === +0;
-0 === -0;

However, these values don't behave completely identically:

1 / +0 === +Infinity
1 / -0 === -Infinity

and clearly +Infinity !== -Infinity.

Then the code does this:

  1. If value is "falsy" (undefined, null, false, +0, -0, NaN, "")
    1. If value is +0 or -0, it returns value
    2. Otherwise, it returns +0
like image 173
Oriol Avatar answered Oct 10 '22 07:10

Oriol