Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if multiple variables is not null, undefined or empty in an efficient way

At the moment I have an if condition like this:

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

I need to use it to check if multiple variables have value (were not left out), but I feel like this is a messy solution and wanted to ask if there is a more efficient way? Maybe additional checks as well?

like image 712
Ilja Avatar asked Sep 17 '15 08:09

Ilja


People also ask

How do you know if a variable is not null or undefined?

To check if a variable is equal to null or undefined , use the loose equality (==) operator. For example, age == null returns true if the variable age is null or undefined . Comparing null with undefined using the loose equality operator returns true .

How do you check if multiple values are null?

To check if multiple variables are not null in JavaScript, use the && (and) operator to chain multiple conditions. When used with boolean values the && operator only returns true if both conditions are met. Copied!

Is it better to use undefined or null?

Only use null if you explicitly want to denote the value of a variable as having "no value". As @com2gz states: null is used to define something programmatically empty. undefined is meant to say that the reference is not existing. A null value has a defined reference to "nothing".

Is null == undefined?

It means null is equal to undefined but not identical. When we define a variable to undefined then we are trying to convey that the variable does not exist . When we define a variable to null then we are trying to convey that the variable is empty.


1 Answers

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

if(variable && variable2 && variable3)

The following values are always falsy in JS:

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

Update:-

If there is a case when you want to execute if block even if the value is 0, you have to add an extra check saying either 0 or some other value.

if((variable || variable === 0) && (variable2 || variable2 === 0) && (variable3 || variable3 === 0))
like image 168
Mritunjay Avatar answered Sep 19 '22 16:09

Mritunjay