Skip to main content

How to Resolve "TypeError: Cannot read properties of undefined (or null) reading 'split'" Error in JavaScript

The TypeError: Cannot read properties of undefined (reading 'split') and its close cousin, ...of null (reading 'split'), are common JavaScript errors. They occur when you try to call the .split() method on a variable that is not a string, but is instead undefined or null.

This guide will explain what the .split() method is, the common reasons your variable might be invalid, and provide the standard, robust solutions to fix this error, from providing default values to using modern optional chaining.

Understanding the .split() Method

The .split() method is a function that exists only on strings. Its purpose is to divide a string into an ordered list of substrings by searching for a specified separator. It returns these substrings in an array.

Correct Usage:

const message = "apple,banana,cherry";

// This works because `message` is a string.
const fruitArray = message.split(',');

console.log(fruitArray);
// Output: ['apple', 'banana', 'cherry']

Understanding the Error: Why undefined or null?

This error happens when the variable you are calling .split() on is not a string. The .split() method simply does not exist on undefined or null values.

The Problem Code (undefined):

let myString; // Declared but not initialized, so it is `undefined`

// ⛔️ Uncaught TypeError: Cannot read properties of undefined (reading 'split')
myString.split(',');

The Problem Code (null):

const dataFromApi = null; // A function or API might return `null`

// ⛔️ Uncaught TypeError: Cannot read properties of null (reading 'split')
dataFromApi.split(',');

Common Causes of the Error

This error typically occurs for a few common reasons:

1. A variable was declared but never assigned a value

let username; // `username` is undefined

// ⛔️ Throws the error
const nameParts = username.split(' ');

Solution: Always initialize variables to a sensible default, like an empty string ("").

2. An object property or array element does not exist

const user = { id: 1 }; // The 'fullName' property is missing

// `user.fullName` is undefined.
// ⛔️ Throws the error
const nameParts = user.fullName.split(' ');

3. A function that was expected to return a string returned something else

function getCsvHeader() {
// This function doesn't return anything, so its result is `undefined`.
}

const header = getCsvHeader(); // `header` is now `undefined`

// ⛔️ Throws the error
const columns = header.split(',');

Solution 1: Provide a Fallback to an Empty String

If a variable might be null or undefined, the easiest way to prevent the error is to provide a default value using the logical OR (||) operator.

const dataFromApi = undefined;

// If `dataFromApi` is falsy (like undefined or null), use an empty string instead.
const message = dataFromApi || '';

// ✅ This is now safe. The .split() method is called on an empty string.
const parts = message.split(',');
console.log(parts);
// Output: ['']
note

Splitting an empty string results in an array containing a single empty string. This is usually acceptable as it is an iterable array.

Solution 2: Use a Conditional Check Before Calling

A more explicit and often more readable solution is to check if the variable is actually a string before you try to call a string method on it. The typeof operator is the perfect tool for this.

const message = undefined;

if (typeof message === 'string') {
const parts = message.split(',');
console.log(parts);
} else {
console.log('Cannot split, because `message` is not a string.');
}

This approach makes your code very robust and its intent clear.

Solution 3: Use Optional Chaining (?.) for Safe Access

For modern JavaScript (ES2020 and newer), the optional chaining operator (?.) is the most concise and elegant solution. It allows you to safely attempt to call a method. If the value on the left is null or undefined, the expression "short-circuits" and returns undefined instead of throwing an error.

const message = undefined;

// The `?.` checks if `message` is null or undefined. Since it is,
// the .split() call is never made. The expression returns `undefined`.
const parts = message?.split(',');

console.log(parts); // Output: undefined

You can combine this with the nullish coalescing operator (??) or logical OR (||) to provide a default value.

const message = null;

// If the optional chain results in `undefined`, the `||` provides a fallback of [].
const parts = message?.split(',') || [];

console.log(parts); // Output: []

Conclusion

The TypeError: Cannot read properties of undefined (or null) reading 'split' error is a clear signal that your variable is not the string you expected it to be.

To fix it, you must add a safeguard before calling the .split() method:

  1. Initialize your variables (Best Practice): The most robust solution is to always initialize your string variables with a default value, like an empty string: let message = "";.
  2. Provide a Fallback: Use the logical OR operator for a quick and safe default: const message = data || '';.
  3. Use a Conditional Check: Use if (typeof message === 'string') for clear and robust code.
  4. Use Optional Chaining (Best for Conciseness): Use const parts = message?.split(',') || []; for a clean, modern, and safe way to perform the operation on a potentially invalid value.