Thursday, 28 July 2016

javascript - Is using == instead of === ok for null/undefined?




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:




  1. Not knowing how == works in case of null / undefined

  2. Knowing how it works but not knowing if the use was intentional (if you actually want to check both null or undefined, or you wanted just check for null 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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...