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

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Photo from Unsplash

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

The "Cannot read property 'split' of null" error occurs when the split() method is called on a variable that stores a null value. To resolve the error, make sure to only call the split() method on strings.

cannot read property split of null

Here is an example of how the error occurs.

index.js
const str = null; // ⛔️ TypeError: Cannot read properties of null (reading 'split') console.log(str.split(','));

To solve the error, provide a fallback if the variable stores a falsy value, e.g. an empty string.

index.js
const text = null; const str = text || ''; console.log(str.split(',')); // 👉️ ['']
The logical OR (||) operator returns the value to the right if the value to the left is falsy (e.g. null).

You can also conditionally check if the variable stores a string before calling the split() method.

index.js
const str = null; // ✅ Check if str is of type string if (typeof str === 'string') { const arr = str.split(','); console.log(arr); } else { console.log('str is not a string'); } // ✅ Use optional chaining const result = str?.split(','); // 👉️ undefined

The first example uses an if statement to check if the str variable stores a value of type string.

The if block is run only if the value is a string, so we can safely call the split() method.

The second example uses the optional chaining (?.) operator, which short-circuits returning undefined if the value to the left is null or undefined.

The operator will only call the split() method if the str variable is not equal to null or undefined.

Conclusion #

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

To avoid getting the error, make sure that the variable stores a string before calling the split() method.

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.