Solve - Cannot read Property 'split' of Undefined in JS

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

banner

Photo by Matt Heaton

Solve - Cannot read Property 'split' of Undefined #

The "Cannot read property 'split' of undefined" error occurs when trying to call the split() method on a variable that stores an undefined value. To solve the error, make sure to only call the split method on strings.

index.js
const str = undefined; // ⛔️ Cannot read properties of undefined (reading 'split') str.split(',');

To solve the error, check if the value is a string, before calling the split() method on it.

index.js
const str = undefined; // ✅ Using if/else statement if (typeof str === 'string') { const arr = str.split(','); // do stuff with arr } else { console.log('str is not a string'); } // ✅ Using optional chaining const r = str?.split(','); // 👉️ undefined

Alternatively you can provide a fallback value if the variable is falsy.

index.js
const address = undefined; // ✅ Provide fallback empty string if falsy const str = address || '';

The first example checks if the value stored in the str variable is of type string before calling the String.split method.

The second example uses the Optional Chaining (?.) operator to short-circuit in case the str variable stores an undefined or null value.

The optional chaining operator will call the split() method if the strvariable is not equal to undefined or null, otherwise it will returnundefined and not throw an error.

The next code snippet shows how to use the logical OR (||) operator to provide a fallback of an empty string if the value to the left of the OR (||) operator is falsy.

Conclusion #

The "Cannot read property 'split' of undefined" error occurs when trying to call the split() method on a variable that stores an undefined value.

To solve the error, make sure to only call the split() method on 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