0

I'm been seeing a lot of articles and even with the underscore or lodash libraries, different ways to evaluate if some variable/const is null or undefined (as the isNil method)... but JS has some way to evaluate that, but, not commonly suggested...

So, I want to know if this code works? or if could break something in my app in some scenario:

let timesCorrect = 0;
let myVal = null;

if(!myVal) timesCorrect++;

myVal = undefined;
if(!myVal) timesCorrect++;

console.log(`Times that the validation is correct ${timesCorrect}`)

myVal = []
if(!myVal) console.warn('ERROR!') // NOT HAPPENS
if(myVal) console.log('Has an empty array or something different to null/undefined')
if(!!myVal) console.log('Has an empty array or something different to null/undefined [Double negation]')

myVal = {}
if(!myVal) console.warn('ERROR!') // NOT HAPPENS
if(myVal) console.log('Has an empty object or something different to null/undefined')
if(!!myVal) console.log('Has an empty object or something different to null/undefined [Double negation]')

I know that instead to use === we can use == to validate if a value is null or undefined... but, the lint rules throw me a warning, and I want to still on this validation.

And I know that could be tricky if we don't know the data type of the variable/const... but, if I know that I expect an object or an array, this validation makes sense for me.

MiBol
  • 1,985
  • 10
  • 37
  • 64
  • 1
    Not really clear what you are asking. There are other falsy values (zero, empty string, NaN and false) you could use other than null or undefined and get same results you are getting just using `if()` – charlietfl Aug 26 '20 at 22:40
  • `v !== null` is true if v is not null ... `v !== undefined` is true when v is not undefined ... that's the simplest checks you can make – Jaromanda X Aug 26 '20 at 22:42
  • 1
    `[null, undefined].includes(variable)` – Taplar Aug 26 '20 at 22:46
  • If one really just needs to distinct either the undefined or the null value from all other possible values, then one should stay with the most simple but always valid non strict comparison `x != null`. There is nothing wrong with that.The linter rule should be ignored, it has its entitlement elsewhere but not in this specific use case. Thus said, the OP's check for either `undefined` or `null` easily can be something like that ... `function isUndefinedOrNull(type) { return (type == null); }` – Peter Seliger Aug 27 '20 at 00:19
  • https://stackoverflow.com/questions/19839952/all-falsey-values-in-javascript – epascarello Aug 27 '20 at 00:19
  • 1
    `myVal !== null` checks for null, `myVal !== undefined` checks for undefined, and `myVal != null` checks for both. If you know that it must be an object or array otherwise, `!myVal` is totally fine as well. You seem to know this already, so what is your question? If your linter complains, either heed its warnings or turn them off if they don't fit your preferred style. – Bergi Aug 27 '20 at 00:52

0 Answers0