I currently have a variable that can be null
as well as undefined
. In both cases I want to leave the function:
if (myvar==null) return;
this works fine but I retrieve warnings from my IDE (VS) because ==
does not care about the type while ===
does. I am aware that ==
is generally be seen as bad style because of this.
Is this the exception from the rule? Should I simply ignore this warning and stick to the better readability or would the following be the recommend action?
if (myvar===null || myvar===undefined) return;
Answer
The problem is the lack of clarification.
If you're writing the code for yourself, it's fine as you know exactly what you're doing. But if a contributor find this code, they could either:
- Not knowing how
==
works in case ofnull
/undefined
- Knowing how it works but not knowing if the use was intentional (if you actually want to check both
null
orundefined
, or you wanted just check fornull
but used==
)
The code should be clear, so often you find programmers adding comments before this check to specify that yes, they know what they're doing, and yes, it was intentional.
Eventually you get tired of that and start to use myvar === null || myvar === undefined
.
It's more verbose, but it's clearer, and doesn't give room to misunderstanding.
Another thing I notice is creating custom fuction for such things, e.g. isNil(myvar)
but despite the verbosity I prefer checking both values.
No comments:
Post a Comment