1

I was poking around the lodash repo and found the following:

if (isCommon && computed === computed) {
     <stuff>
}

Here,

  • isCommon is a boolean initially set to true and then reset to false conditionally on some checks;
  • while computed is obtained by iterating over an array (for (let value of array)) and possibly applying a function iteratee to the current value value.

My question:

Why is that if clause not simply if (isCommon)?

Elaboration (of one possible answer)

The Mozilla operator-precedence table tells me that

  • strict equality === has precedence 11,
  • higher than the precedence of 7 for the && operator

This means, presumably, that the boolean check inside the if is parsed as isCommon && (computed === computed).

Most of the time that second arm will be true, as x === x even for funky "values" like null or undefined. The only other option I can think of is that applying the function iteratee to value to produce computed might make a NaN. In that case the strict equality will evaluate to false; in node:

> x=Math.abs("boo"); 1 && x === x
false

Is this it? Is the somewhat strange (to me) shape of the if clause meant to guard against this eventuality?

grobber
  • 1,083
  • 1
  • 9
  • 20
  • 1
    The only thing that jumps to mind is that perhaps it relates to something like checking for `NaN` in a legacy way? – DBS Jun 04 '21 at 12:56
  • Thanks: `NaN` is what came to my mind too, as mentioned. Someone seems to have suggested [this](https://stackoverflow.com/a/27144366/11064961), which makes the same suggestion. My question was more along the lines of "what else could this be for", but I suppose closing it is fair enough. – grobber Jun 04 '21 at 13:05

0 Answers0