Categories
Development Java Javascript

What’s the common way to check if a field is null or undefined (but not zero or empty string) in Javascript? [duplicate]

This question already has an answer here:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *