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

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

banner

Photo by Ales Krivec

Solve - Cannot read Property 'split' of Null #

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.

index.js
const str = null; // โŒ Cannot read properties of null (reading 'split') console.log(str.split(','));

To avoid getting 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 || '';

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 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 executed 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.

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