I’m trying to cleanup some code (fix jshint warnings).
What’s the best replacement for
if (x == undefined) {...}
?
I’m using underscore.js, is the following equivalent:
if (x === null || _.isUndefined(x)) {...}
Or am I missing some edge cases?
What is equal (==) to undefined? (assuming nobody did var undefined = 'asdf' or anything evil like that).
With
x == undefinedyou actually check for two values ofx–undefineditself andnull. Take note, though, that absence of declaredxvariable will trigger an error here; to prevent this, use…But I actually think the true meaning of this warning is that you shouldn’t check for both
nullandundefinedin one branch of code, as these are different values.Yet if you feel safe about this, you can turn off these particular checks in JSHint, with
eqnulloption. Then…… will check both for
nullandundefined, yet won’t trigger the warning. Note, though, that== undefinedcomparisons are not ‘covered’ by this option.As a sidenote, underscore’s
isUndefinedmethod is an interesting piece of code:It’s essentially the same as simple
obj === undefined, yet covers one special case: when someone decided that it’s a good idea to overwrite the value ofundefinedin their script. Asvoidconstruct always returns “the realundefined“, this function will work correctly even in this situation.