TypeError: Cannot read Property 'split' of Undefined in JS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

TypeError: Cannot read Property 'split' of Undefined in JS #

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.

cannot read property split of undefined

Here is an example of how the error occurs.

index.js
const str = undefined; // ⛔️ TypeError: 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.

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 str variable is not equal to undefined or null, otherwise it will short-circuit returning undefined.

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

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

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.