1

Based on this answer I know I can check if a property exists using the in operator. So I see in a lot of code that it is common to use, for example:

if ("gapi" in window) {
    gapi.login(...);
}

But wouldn't be better to do it this way?

if (window.gapi) {
    gapi.login(...);
}

The only difference that I am aware of is that the second one will return false if the variable exists but its value is undefined, false, 0, null or other value that evaluates to false; and the first one will return true, right?

So, is there any other difference? Which one should I use?

Community
  • 1
  • 1
Pablo Matias Gomez
  • 6,614
  • 7
  • 38
  • 72
  • With the latter, what if `window.gapi` were 0, false, null, etc? – Marty May 10 '16 at 23:35
  • @Marty yes, that is what I stated in my last paragraph before the question – Pablo Matias Gomez May 10 '16 at 23:35
  • Your last paragraph strictly mentions `undefined` from what I understand. – Marty May 10 '16 at 23:37
  • @Marty you are right, I had those values in mind but didnt write all of them. I updated the question. Thanks – Pablo Matias Gomez May 10 '16 at 23:45
  • Your question is unusual now as it reads something like "what are the differences between these two things excluding this significant list of differences?". – Marty May 10 '16 at 23:46
  • @Marty yes but my point is that is really common to use the first one but I think that because of that difference, the second one should be better. Then I think that maybe there are other differences that make the first one "better" – Pablo Matias Gomez May 10 '16 at 23:47
  • As you've hinted in your responses to the answers below, it depends entirely on the use case. It's unlikely that you would want to attempt to "login" with something other than a valid string with length greater than zero, but in another instance you might be happy to accept `null` as a value. – Marty May 10 '16 at 23:49

2 Answers2

6

Yes there's a significant difference. What if gapi is falsy (0, false, empty string, null)? That will skip over the block.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
2

Use the first one. With the second, it will return false if window.gapi happens to be 0, false, '', null, undefined, etc. This means that even if window.gapi exists, your code may not think it does.

Feathercrown
  • 2,547
  • 1
  • 16
  • 30