Imagine having an object property (let's call it
arrThatCouldBeNullOrUndefined: SomeObjType
) in your Angular component.
You aim to perform an array operation (let's say filter()
operation) on its data: DataType[]
object and save the result in another property (let's name it filteredArr: DataType[]
) as demonstrated below:
this.filteredArr = this.arrThatCouldBeNullOrUndefined.data.filter(item => this.someFilterCondition(item));
To prevent any TypeErrors (e.g., any undefined
or null
references), you could opt for either of the following approaches when writing the code.
Approach 1: Utilize a Safe operator (?.)
this.filteredArr = this.arrThatCouldBeNullOrUndefined?.data?.filter(item => this.someFilterCondition(item));
or
Approach 2: Employ the logical and operator (&&)
if(this.arrThatCouldBeNullOrUndefined && this.arrThatCouldBeNullOrUndefined.data) {
this.filteredArr = this.arrThatCouldBeNullOrUndefined.data.filter(item => this.someFilterCondition(item))
}
Questions:
- Under what circumstances should the above approaches be used?
- Which approach is generally recommended to use (or avoid) as a default option?