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?
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 .
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!
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".
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.
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!)
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With