Borislav Hadzhiev
Sat Oct 23 2021·2 min read
Photo by Matt Heaton
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.
Here is an example of how the error occurs.
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.
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.
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.
split()
method if the str
variable 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.
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.