Consider that I have an array of objects property (say arrThatCouldBeNullOrUndefined: SomeType[]
) in my angular component.
I want to perform some array operation (say filter()
operation) on it and store the value in some other property (say filteredArr: SameType[]
) as shown below
this.filteredArr = this.arrThatCouldBeNullOrUndefined.data.filter(item => this.someFilterCondition(item));
To avoid any TypeErrors (i.e., any undefined
or null
references) I could choose either of the below approches to write the code.
Approach 1: Use a Safe operator (?.)
this.filteredArr = this.arrThatCouldBeNullOrUndefined?.data?.filter(item => this.someFilterCondition(item));
or
Approach 2: Use logical and operator (&&)
if(this.arrThatCouldBeNullOrUndefined && this.arrThatCouldBeNullOrUndefined.data) {
this.filteredArr = this.arrThatCouldBeNullOrUndefined.data.filter(item => this.someFilterCondition(item))
}
My Queries:
- When should we use the either of the approaches?
- Which approach is the best to follow (or avoid) by default?