Reputation: 3159
Is there a better way in Javascript to do null check on multiple elements I want to
a=null; b=null;....n=null;
So in total I have 14 variables set to null initially and I want to apply just one solution to all of them if they are ```null``.
if (a=== null && b=== null&& c=== null&& d=== null&& e=== null &&...&& n===null){
// set some field to false
}
is there a better way to check for null, as this may get cumbersome if we have more arrays added Thanks!
Upvotes: 0
Views: 303
Reputation: 191976
Create a an array of arrays, iterate it using Array.every()
, and do something if all item values are null
:
if([a, b, c, ... n].every(a => a === null)) {
// set some field to false
}
Upvotes: 3
Reputation: 1052
If you're new to JS, in JS, values can be "falsey" or "truthy". if
/ while
/ for
will run if the value it's supposed to evaluates to "truthy." There are few "falsey" values in JS, and the rest are considered "truthy." The false values are:
undefined
0
NaN
null
''
false
(I believe I got them all. Think of "six sins": there are six of these)
So check the following code, and what their outcomes are:
if(0) console.log('yay') // won't run
if(false) console.log('yay') // won't run
if(null) console.log('yay') // won't run
if('') console.log('yay') // won't run
if(NaN) console.log('yay') // won't run
if([]) console.log('yay') // will run
if('0') console.log('yay') // will run
This is a long winded way of saying if you want to do something based on whether array is empty or not, try the following:
let arr = [1,2,3,4]
if(arr.length){
//do stuff if array is not empty
} else {
// do stuff if array is empty
}
Now to actually solve the problem for you, do the following:
const masterArray = [a, b, c, d, ... , n];
let length = 0;
masterArray.forEach(subarr=>{
length += subarr.length;
})
//At this point, if no array had any elements, length would be 0
if(length === 0){
// do stuff
}
Upvotes: 1