Solve - Cannot read property 'filter' of Null in JS

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

banner

Photo by Bobby Hendry

Solve - Cannot read property 'filter' of Null #

The "Cannot read property 'filter' of null" error occurs when calling the filter() method on a null value. To solve the error, initialize the value for the variable to an empty array or make sure you only call the filter method on arrays.

index.js
const arr = null; // ⛔️ Cannot read properties of null (reading 'filter') arr.filter(element => element);

Here are examples of how to initialize the value for the arr variable to an array, or make sure the variable stores an array before calling the filter method.

index.js
const fromDb = null; const arr = fromDb || []; // ✅ Initialized to array const result1 = arr.filter(element => element); // ✅ Check if array if (Array.isArray(arr)) { const result2 = arr.filter(element => element); } else { console.log('arr is not an array'); } // ✅ Initialize to empty array if falsy const result3 = (arr || []).filter(element => element); // ✅ Use ternary operator const result4 = arr ? arr.filter(element => element) : [];

When declaring the arr variable, we set it to an empty array if the value of the fromDb variable is falsy.

We used the logical OR (||) operator to provide the fallback value. If the value to the left of the operator is falsy (e.g. null), the operator returns the value to the right.

The second example uses the Array.isArray method to make sure to only call the Array.filter method on arrays.

The third example provides a fallback if the value stored in the arr variable is falsy right before calling the filter method.

The fourth example uses the ternary operator, which is very similar to an if/else statement.

If the expression before the question mark evaluates to a truthy value, the value to the left of the colon is returned, otherwise the value to the right of the colon is returned.

If the value stored in the arr variable is falsy (e.g. null), we return an empty array, otherwise we return the result from calling the filter method.

Conclusion #

The "Cannot read property 'filter' of null" error occurs when calling the filter() method on a variable that stores a null value.

To solve the error, initialize the variable to an empty array before calling the filter method.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee