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.