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

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

banner

Photo by Warren Wong

Solve - Cannot read property 'includes' of Undefined #

The "Cannot read property 'includes' of undefined" error occurs when calling the includes() method on an undefined value. To solve the error, make sure to only call the method on data types that implement it - arrays and strings.

index.js
const arr = undefined; // ⛔️ Cannot read properties of undefined (reading 'includes') arr.includes('example'); const str = undefined; // ⛔️ Cannot read properties of undefined (reading 'includes') str.includes('example');

To solve the error, provide a fallback for the value and only call the method if the value is of the expected type.

Here are some examples of how to avoid the error when using the includes() method with arrays or strings.

index.js
// 👇️👇️👇️ ARRAY EXAMPLES const fromDb = undefined; // ✅ Initialize to Empty Array if falsy const arr = fromDb || []; // ✅ Using optional chaining const r1 = arr?.includes('example'); console.log(r1); // 👉️ false // ✅ Using Array.isArray if (Array.isArray(arr)) { const r2 = arr.includes('example'); } // ✅ Provide fallback in place const r3 = (arr || []).includes('example'); // 👇️👇️👇️ STRING EXAMPLES const str = fromDb || ''; // ✅ Using optional chaining const r4 = str?.includes('example'); console.log(r4); // 👉️ false if (typeof str === 'string') { const r5 = str.includes('example'); } // ✅ Provide fallback in place const r6 = (str || '').includes('example');

We used the logical OR (||) operator to provide a fallback if the value to the left of the operator is falsy (e.g. undefined).

If the value to the left is falsy, the logical OR (||) operator returns the value to the right.

The optional chaining (?.) operator allows us to avoid getting an error, because if the reference is equal to undefined or null, it short-circuits returning undefined.

The Array.isArray method and the typeof str === 'string' comparisons can be used to verify that the data type is an array or a string before calling theincludes() 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 undefined" error occurs when calling the includes() method on an undefined value.

To solve the error, make sure to only call the includes() method on data types that support it - arrays and 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