I am working on Angular project and time to time I used to have check undefined or null over Object or it's properties. Normally I use lodash _.isUndefined() see example below:
this.selectedItem.filter(i => {
    if(_.isUndefined(i.id)) {
      this.selectedItem.pop();
    }
})
I couldn't see any problem with it. But I had discussion with my colleague during review of above code. He was telling me that if i gets undefined before the if statement then it will throw the exception. Instead he suggested me to always check i or i.id like this:
if(!!i && !!i.id) {
      this.selectedItem.pop();
}
I am convinced what he was trying to say unlike his way of checking undefined in above code. But then I was thinking what is the purpose of lodash _.isUndefined?
Could anyone please let me know what is the best or clean way to do it. Because for me !!i && !!i.id is not readable at all.
Many thanks in advance.
So the correct way to test undefined variable or property is using the typeof operator, like this: if(typeof myVar === '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.
Difference Between undefined and null Though, there is a difference between them: undefined is a variable that refers to something that doesn't exist, and the variable isn't defined to be anything. null is a variable that is defined but is missing a value.
Say, if a string is empty var name = "" then console. log(! name) returns true . this function will return true if val is empty, null, undefined, false, the number 0 or NaN.
You can use _.isNil() to detect undefined or null. Since you're using Array.filter(), you want to return the results of !_.isNil(). Since i is supposed to be an object, you can use !_.isNil(i && i.id).
Note: you are using Array.filter() as Array.forEach(). The callback of Array.filter() should return a boolean, and the result of the filter is a new array.
const selectedItem = [
  undefined,
  {},
  { id: 5 },
  undefined,
  { id: 7 },
];
const result = selectedItem.filter(i => !_.isNil(i?.id));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
You can also use _.reject() and save the need to add !:
const selectedItem = [
  undefined,
  {},
  { id: 5 },
  undefined,
  { id: 7 },
];
const result = _.reject(selectedItem, i => _.isNil(i?.id));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
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