18

Sorry for what I'm sure had have been asked in the past, but it's very hard to search for a question like this. "!=" and "!==" are not exactly search friendly. If anyone knows a duplicate question you can point me to it.

What is the difference between doing myVar != null and myVar !== null? I know that != is not equal and !== is not equal value or not equal type, but when comparing to null is there ever a case where they would return different results? Is one better to use than the other?

Nick
  • 4,556
  • 3
  • 29
  • 53
  • http://stackoverflow.com/questions/523643/difference-between-and-in-javascript?rq=1 – 10100111001 Aug 16 '16 at 14:40
  • I searched for "javascript scrict inequality vs inequality" and found stuff, but knowing the name of things can be hard. I have no idea how people search for `? :` the first time they see `x = y ? z :w;` – David Ehrmann Aug 16 '16 at 14:45
  • look here for detailed explanation: https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch4.md – Yasin Yaqoobi Aug 16 '16 at 14:45

1 Answers1

46

The answer to the specific question about whether there's ever a case where != and !== comparisons involving null get different answers is yes:

undefined != null  // false
undefined == null  // true

undefined === null // false
undefined !== null // true

The rules for == and != explicitly include a clause that stipulates that null and undefined are the same.

Personally — that is, in my code — that fact is a reason for using != (or ==) when checking for null in cases where undefined should be treated the same way (which is a pretty common situation).

rmcsharry
  • 5,363
  • 6
  • 65
  • 108
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 2
    Also, Lodash's [isNil](https://lodash.com/docs/4.17.4#isNil) function checks whether the given value is 'nullish' (that is `null` or `undefined`) and behind the scenes does exactly that: checks if the given value `== null`. – Neurotransmitter Jan 10 '18 at 13:52