0

What would be a simple way other than having many if...else functions and hardcoding the variable names as string. Let say we have 10 variables that may or may not contain some values. I want to be able to return a list of all those variable names that are null.

Instead of doing:

if (x == null) return "x"

for all the variables, is there a better way that I can do this? Looking for javascript/jquery or underscore methods.

Julius Knafl
  • 429
  • 3
  • 14

3 Answers3

1

You cannot get a list of variables out of thin air, so you would need to test on an object's properties.

This should work on objects. It takes all keys and filter them through isNUll

console.log(_.filter(_.keys(object),(key)=>{
    return _.isNull(object[key]);
}));

You can read more about getting the impossibility (or very improbability) of getting current scope variables: Getting All Variables In Scope

Salketer
  • 14,263
  • 2
  • 30
  • 58
1

If you follow @Pointy's advice in the comments and make your variables properties of an object, you will be able to do the following :

const person = {
    firstName: "John",
    lastName: null,
    age: null
}

for(let prop in person) {
    if(person[prop] === null)  console.log(prop + ' is null');
}

And if you want to check the values of some globally declared variables, it won't be much less verbose but much more elegant than multiple ifs :

['x', 'y', 'z'].map((propName) => {
    if(window[propName] === null || window[propName] === undefined) 
        console.log(prop + ' is not defined');
});
Logar
  • 1,248
  • 9
  • 17
1

You should maintain an object of the variables x,y like this (in ES6 for example)

var obj = {
  x,
  y
}

And then filter out the null properties

Object.keys(obj).filter(k => obj[k] === null)

An array of null variable names will be returned.

Xhua
  • 118
  • 1
  • 7