Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use (undefined || null) to check if my variable is null or undefined?

In my Javascript code I'm checking if a variable is undefined (not the value undefined but the variable not defined) or null. To trim the code I'm using an operator. This is how I do it:

if (myVariable === (undefined || null)) {
    // Do something.
}

A friend of mine told me once, that I should rather split the checks into:

if (myVariable === undefined || myVariable === null) {
    // Do something.
}

Is there really any difference between these two approaches? If yes, which one should I use and why?

like image 898
dwettstein Avatar asked Jul 18 '14 07:07

dwettstein


1 Answers

Is there really any difference between these two approaches?

Yes.

myVariable === (undefined || null)

is equivalent to

myVariable === null

which is only true if myVariable is null, and false if myVariable is undefined. Whereas:

myVariable === undefined || myVariable === null

returns true if myVariable is either undefined or null.

If yes, which one should I use and why?

Neither (probably), even if the answer was yes. If you are trying to determine whether a variable exists or not, you can only test for global variables as they are properties of the global object:

// In global code
var window = this;

// Later…
if (varname in window) {
  // varname is a global variable or property
}

Within a function execution context, you can only reliably test for a variable using try..catch:

try {
  var blah = foo;
} catch (e) {
  // foo is probably not a variable in scope
}

But that is almost certainly not a good idea. See JavaScript check if variable exists (is defined/initialized) - Which method is better?.

You should probably be doing:

if (typeof varname == 'undefined' || varname === null) {
  // varname either does't exist or has a value of undefined or null.
}

The tests need to be in that order so that if varname hasn't been declared or otherwise created, the typeof test fails before the null test, which would otherwise throw an error.

like image 79
RobG Avatar answered Sep 26 '22 14:09

RobG