filter() in javascript
Let's start with a question.
const filteredMetaData = metaData.filter((md) => md.Code== 2010));
A. If(filteredMetaData.length){
}
B. If(filteredMetaData){
}
Which option should be used when you want to enter inside the if condition when the filter returns some result?
Important facts about filter.
1. It is used on the array and it filters the item of that array based on a given condition. In our question above, it will return all items from metaData that have Code property value 2010.
2. It does not change the original array. The result from the filter is a brand-new array thus it helps achieve immutability. Mutate or mutability means change, the opposite of it, immutability means no change. No change in the original array.
3. If the filter condition is not met, it returns an empty array. Remember, the output of the filter is always a new array.
Back to the question,
If we use option B, when the filter has no matching condition, it returns an empty array that is always true (it's not null).
Hence option A is the correct answer.
Also, when we use property such as .length, we should always make sure that the value on which we apply length should never be null or undefined.
In our case filteredMetaData
will either be an empty array or an array with some items, in either case, it's not null or undefined and hence safe to use.