0

I know I can't do if (!obj.x) because if obj.x is 0 or "", it will be "truthy".

Option 1: I could do if (obj.x === null || obj.x === undefined).

Option 2: But could I just do if (obj.x == null)?

Just to be clear, I want a condition that is true when obj.x is null or undefined, but false for any other value.

According to the comments, both options are equivalent but option 2 is more clear. I agree.

EDIT:

Someone pointed out that there are similar questions (see links above), but in this case I was thinking of fields, rather than variables. The difference is that fields can be undefined and there is no runtime error when using them. I updated my question accordingly.

EDIT 2:

This question was closed because there are similar questions. I think there is a slight difference here, because in my question I'm checking a field/property of an object, not a variable, so the typeof operator is not needed.

Ferran Maylinch
  • 10,919
  • 16
  • 85
  • 100
  • 2
    Yes, those two are exactly equivalent. – Ry- Nov 29 '19 at 08:35
  • 3
    I wouldn't recommend it. Better not to rely on `==`, using `===` makes the code a *lot* more intuitive to read - using two separate `===` tests is probably the better way to go – CertainPerformance Nov 29 '19 at 08:35
  • This question isn't asking anything that isn't already addressed by the canonical question. The only difference is that when checking a standalone variable, you need to use `typeof` *if* the variable might not have been declared yet. – CertainPerformance Nov 29 '19 at 11:59
  • `!= null` and `== null` is a common shortcut for checking undefined & null. Otherwise you should use `===` and `!==` respectively. – Andreas Herd Nov 29 '19 at 13:07
  • 1
    “Actually, it doesn't make sense to check `variable === undefined` since it would throw an error when the variable is undefined” is incorrect – `undefined` is a value, like `null`, and variables can have it. It’s much rarer to not know whether a variable has been declared. – Ry- Nov 30 '19 at 03:57
  • Thanks Ry, you're right. I removed that sentence. – Ferran Maylinch Nov 30 '19 at 16:09

0 Answers0