Skip to content
Advertisement

Checking ‘undefined’ or ‘null’ of any Object

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.

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement