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:

JavaScript

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:

JavaScript

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.

JavaScript
JavaScript

You can also use _.reject() and save the need to add !:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement