0

I have a number of variables in my script, each of which could contain a value, undefined or null.

I've noticed alot of repetative code checking for undefined and nulls, can a common function be created?

I have created a common fucntion to check all variables are not undefined or null:

JS Original:

var testa;
var testb;
var testc;

if ((typeof testa == "undefined" || testa == null) && (typeof testa == "undefined" || testb == null) && (typeof testc == "undefined" || testc == null)) {
    //Do something ///////////
}

JS New:

var testa;
var testb;
var testc;

if (checkValues(testa) && checkValues(testb) && checkValues(testc)) {
    //Do something ///////////
}

function checkValues (v) {
    return (v == "undefined") || (v == null);
}

Which works. However what if testa contains a value, and testb and testc are null or undefiend? e.g:

if ((typeof testa == "undefined" || testa == null) && (typeof testa != "undefined" || testb != null) && (typeof testc != "undefined" || testc != null)) {
    //Do something ///////////
}
user3731438
  • 283
  • 7
  • 18
  • Then it will not enter in if block because you are using and condition. – Amy Nov 08 '14 at 10:21
  • There are a number of things that can go wrong with `checkValues`. Recommended reading: http://stackoverflow.com/questions/359494 Also, http://stackoverflow.com/questions/3390396/ – blgt Nov 08 '14 at 10:21
  • You can do something like `function isUndefOrNull(x) { return x === null || x === undefined; }` – The Paramagnetic Croissant Nov 08 '14 at 10:24
  • 1
    Be aware of the difference between '==' and '===' when comparing nulls. Also have in count 'Nan' isnt undefined nor null, and you maybe want to check it too (check for 'Nan' is tricky, btw) – Sergeon Nov 08 '14 at 10:31
  • You forgot the `typeof` keyword in your `checkValues` function. It's looking for a string currently. – Bergi Nov 08 '14 at 13:02

2 Answers2

0

This depends on your use, according to your given condition "what if testa contains a value, and testb and testc are null or undefined" the as per your condition it will return false.

0

You don't need a function to do that. == null will be true for both undefined and null values, so you need only this:

if (testa == null && testb == null && testc == null)

I assume you don't want to deal with undeclared variables, for which you need the typeof … == "undefined" test (and cannot use a helper function), see also this answer

Community
  • 1
  • 1
Bergi
  • 513,640
  • 108
  • 821
  • 1,164