2

I was reading the source code of core-js and I saw the following:

if (value != value) return true;

What does it actually mean? When exactly value won't be equal to itself?

vesii
  • 2,760
  • 4
  • 25
  • 71
  • it looks like an old `NaN` check. please see duplicate above. – Nina Scholz Nov 24 '22 at 14:54
  • @NinaScholz This question isn't really a duplicate of that question. The questions are completely different and the answers just happen to be (somewhat) similar. CertainPerformance's answer shows that this could be something that isn't a NaN check. – Michael M. Nov 24 '22 at 14:58
  • The comment on the line above the quoted line explicitly says that it's a NaN check. – Guillaume Brunerie Nov 24 '22 at 15:08
  • 1
    @MichaelM., for the other case this would be the duplicate question: https://stackoverflow.com/q/48270127/1447675 – Nina Scholz Nov 24 '22 at 15:11
  • @MichaelM. no, `value` will be exceptionally likely ***not*** be a getter property which changes on reads. It is exceptionally likely to be a *value*. Unless you have really, really, *really*, ***really*** strong evidence to suggest that the core-js library i̶s̶ ̶i̶n̶s̶a̶n̶e̶ will for some reason decide to define a getter property and check it by reading it twice. As opposed to getting a value and checking for `NaN`. In general, I've never *once* in my entire life seen any serious code use a getter property and check it against itself. I've *only* seen it as "haha, you can do this" example. – VLAZ Nov 24 '22 at 15:16
  • 1
    @MichaelM. also, given that the line of code ***that defines `value`*** is `value = O[index++];` it is literally impossible for `value` to be a getter property. It's always ***guaranteed*** to be a plain value. The comment right above `value !== value` also reads "NaN check". Of course, if you have evidence that it's not checking for `NaN`, feel free to share. – VLAZ Nov 24 '22 at 15:20
  • This is used by lodash as part of `isEqual` logic (well it actually uses `!==` but I'm guessing there isn't a difference in usage). The following definitely made my head spin a little when I read it: `return value !== value && other !== other` https://github.com/lodash/lodash/blob/master/.internal/baseIsEqual.js – Simon_Weaver Jul 22 '23 at 19:31

1 Answers1

4

It could be if:

  • value is NaN

console.log(NaN != NaN);
  • value is actually a getter on the global object, and it returns something different each time:

let i = 0;
Object.defineProperty(window, 'value', { get: () => i++ });

console.log(value != value);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320