Verifying that multiple variables are not null, undefined, or empty in an efficient way

At the moment, I have an if condition:

if( (variable != null && variable != '' && !variable) && (variable2 != null && variable2 != '' && !variable2) && (variable3 != null && variable3 != '' && !variable3) //etc.. ) 

I need to use it to check if several variables matter (it was not excluded), but I feel that this is a dirty solution and wanted to ask if there is a more efficient way? Perhaps additional checks?

+6
source share
6 answers

Since if(variable) ignores any falsy value, this will work for you

 if(variable && variable2 && variable3) 

The following values ​​are always false in JS:

 false. 0 (zero) "" (empty string) null. undefined. NaN (a special Number value meaning Not-a-Number!) 

Update: -

If there is a case where you want to execute, if the block, even if the value is 0, you must add an additional check, specifying either 0 or another value.

 if((variable || variable === 0) && (variable2 || variable2 === 0) && (variable3 || variable3 === 0)) 
+19
source

I assume that you are checking true values? If so, you can simply do:

variable && variable2 && variable3

+3
source

If your variables contain some values ​​that are true, like a string, and this is considered positive in your state, you can simply check with Array.prototype.every() ...

 if (![var1, var2, var3].every(Boolean)) { throw new exc; } 

Which will verify that each variable has a true value.

+2
source

See JavaScript: What is the difference between if (!x) and if (x == null) ?

! the variable will be true for all false values, so you only need to

 if(variable1 && variable2 && variable3 && ...) 
0
source

If IE support doesn't matter to you, you can do the following

 var a = 5; var b = null; var c = undefined; if ( [a,b,c].includes(undefined) || [a,b,c].includes(null) ) { console.log("You f*d up") } 

For more information check MDN reference

Or you can use lodash

 var a = 5; var b = null; var c = undefined; if ( _.some([a,b,c], el => _.isNil(el)) ) { console.log("You f*d up") } 
 <script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script> 
0
source

Long arm -

  if (var1 !== null || var1 !== undefined || var1 !== '') { let var2 = var1; } 

Short arm -

  const var2 = var1 || ''; 
0
source

All Articles