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

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

Solve - Cannot read property 'includes' of Null #

The "Cannot read property 'includes' of null" error occurs when the includes() method is called on a variable that stores a null value. To solve the error, make sure you're calling the method on the correct data type - array or string.

index.js
const arr = null; // โ›”๏ธ Cannot read properties of null (reading 'includes') console.log(arr.includes('test'));

To avoid getting the error, initialize the value to an empty array or empty string before calling the includes() method and check that the value is of the correct type.

These examples show how to avoid getting the error when working with arrays or strings.

index.js
// ๐Ÿ‘‡๐Ÿ‘‡๏ธ๐Ÿ‘‡๏ธ๏ธ WITH ARRAYS const fromDb = null; // โœ… Provide empty array as fallback const arr = fromDb || []; // โœ… Using optional chaining (?.) const ex1 = arr?.includes('test'); // โœ… Using Array.isArray if (Array.isArray(arr)) { const ex2 = arr.includes('test'); } // โœ… Provide fallback value in place const ex3 = (arr || []).includes('test'); // ๐Ÿ‘‡๏ธ๐Ÿ‘‡๏ธ๐Ÿ‘‡๏ธ WITH STRINGS // โœ… Provide empty string as fallback const str = fromDb || ''; // โœ… Using optional chaining (?.) const ex4 = str?.includes('test'); // โœ… Using typeof if (typeof str === 'string') { const ex5 = str.includes('test'); } // โœ… Provide fallback value in place const ex6 = (str || '').includes('test');

We used the logical OR (||) operator when initializing the arr and str variables.

The logical OR operator returns the value to the right if the value to the left is falsy (e.g. null).

An easy way to avoid getting the error is to use the optional chaining (?.) operator.

The (?.) operator short-circuits if the reference is equal to null or undefined, otherwise it calls the method.

Alternatively, you can use the Array.isArray method or the typeof operator to determine if the value is an array or string before calling the includes() method.

The last example shows how to use the logical OR (||) operator to provide a fallback value right before calling the includes() method

Conclusion #

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

To avoid getting the error, make sure to only call the method on data types that implement it - arrays or strings.

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