Borislav Hadzhiev
Sat Oct 23 2021·2 min read
Photo by Bobby Hendry
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.
Here is an example of how the error occurs.
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.
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.
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.
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.