Cannot read properties of undefined (reading 'split') in JS

avatar
Borislav Hadzhiev

Last updated: Mar 3, 2024
6 min

banner

# Table of Contents

  1. Cannot read properties of undefined (reading 'split') in JS
  2. Cannot read properties of null (reading 'split') in JS

# Cannot read properties of undefined (reading 'split') in JS

The "Cannot read properties of undefined (reading 'split') in JS" 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(',');

cannot read properties of undefined reading split

We attempted to call the String.split() method on an undefined value which caused the error.

# Check if the variable is a string before calling split

You can use the typeof operator to check if the variable stores a string before calling the split() method.

index.js
const str = undefined; if (typeof str === 'string') { const result = str.split(','); console.log(result); } else { // ๐Ÿ‘‡๏ธ this runs console.log('The variable does NOT store a string'); }

check if variable is string before calling split

The code for this article is available on GitHub

The if block is only run if the variable stores a string, otherwise, the else block runs.

# Using optional chaining (?.) to solve the error

You can also use the optional chaining operator to short-circuit if the reference is nullish.

index.js
const str = undefined; const result = str?.split(',') || []; console.log(result); // ๐Ÿ‘‰๏ธ [] console.log(str?.split(',')); // ๐Ÿ‘‰๏ธ undefined

using optional chaining to solve the error

The code for this article is available on GitHub

The optional chaining (?.) operator short-circuits, instead of throwing an error, if the value on the left is nullish (undefined or null).

# Check if the variable doesn't store undefined

You can also explicitly check if the variable doesn't store an undefined value in an if statement.

index.js
const str = undefined; if (str !== undefined) { const result = str.split(',') console.log(result) } else { console.log('The variable has an undefined value') }

check if the variable does not store undefined

We explicitly check that the variable doesn't store an undefined value.

If the variable doesn't store an undefined value, the if block runs, otherwise, the else block runs.

# Providing a fallback value if the variable stores undefined

You can use the logical OR (||) operator to provide a fallback value of an empty string if the variable stores an undefined value.

index.js
const str = undefined; const result = (str || '').split(','); console.log(result); // ๐Ÿ‘‰๏ธ ['']

providing fallback value if the variable stores undefined

The code for this article is available on GitHub

The logical OR (||) operator returns the value to the right if the value to the left is falsy (e.g. undefined).

However, note that the split() method will return an array containing an empty string in this case.

If the separator is not contained in the string, the split() method returns a single element array containing the entire string.

index.js
const str = undefined; const result = (str || 'abc').split(','); console.log(result); // ๐Ÿ‘‰๏ธ [ 'abc' ]

# Use the ternary operator to solve the error

You can also use the ternary operator to solve the error.

index.js
const str = undefined; const result = typeof str === 'string' ? str.split(',') : []; console.log(result); // ๐Ÿ‘‰๏ธ []
The code for this article is available on GitHub

The ternary operator is very similar to an if/else statement.

If the expression before the question mark evaluates to a truthy value, the value to the left of the colon is returned, otherwise the value to the right of the colon is returned.

If the value stored in the str variable is falsy (e.g. undefined), we return an empty array, otherwise, we return the result of calling the split() method.

# Other common reasons the error occurs

Common reasons the error occurs are:

  1. Calling the method on a class property that is not initialized to a string
  2. Calling the method on an array index that doesn't exist

# Solve the error when working with arrays

Here's an example that shows the error being thrown when using arrays.

index.js
const arr = []; // โ›”๏ธ Cannot read properties of undefined (reading 'split') arr[0].split(',');

To solve this, you have to make sure the element at the index is available and of type string.

index.js
const arr = []; const result = typeof arr?.[0] === 'string' ? arr[0].split(',') : []; console.log(result); // ๐Ÿ‘‰๏ธ []

Before calling the split() method, we check if the array element at the specified index is a string.

# Solve the error when working with classes

If using classes, you have to declare the class property and set it to an empty string before accessing it.

index.js
class Person { // โœ… Initialize from parameters constructor(name) { this.name = name; } splitName() { return this.name.split(' '); } } const p1 = new Person('James Doe'); console.log(p1.splitName()); // ๐Ÿ‘‰๏ธ [ 'James', 'Doe' ]
The code for this article is available on GitHub

We initialized the value of the name class property. Had we not done that, we would get the error when trying to access the property.

# Track down where the variable got assigned an undefined value

If the error persists, you have to track down where the variable got assigned an undefined value.

A common source of undefined values is assigning the output of a function that doesn't return anything to a variable.

Many built-in methods that mutate an object in place return undefined.

All JavaScript functions that don't return a value return undefined.

You might be accessing an array at an index that doesn't exist or a non-existent property in an object.

# Cannot read properties of null (reading 'split') in JS

The "Cannot read properties of null (reading 'split')" 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(','));

We tried to call the split() method on a null value which caused the error.

# Check if the variable is a string before calling split

You can use the typeof operator to check if the variable stores a string before calling the split() method.

index.js
const str = null; if (typeof str === 'string') { const result = str.split(','); console.log(result); } else { // ๐Ÿ‘‡๏ธ this runs console.log('The variable does NOT store a string'); }
The code for this article is available on GitHub

The if block is only run if the variable stores a string, otherwise, the else block runs.

# Using optional chaining (?.) to solve the error

You can also use the optional chaining operator to short-circuit if the reference is nullish.

index.js
const str = null; const result = str?.split(',') || []; console.log(result); // ๐Ÿ‘‰๏ธ [] console.log(str?.split(',')); // ๐Ÿ‘‰๏ธ undefined

The optional chaining (?.) operator short-circuits, instead of throwing an error, if the value on the left is nullish (null or undefined).

# Check if the variable doesn't store null

You can also explicitly check if the variable doesn't store a null value in an if statement.

index.js
const str = null; if (str !== null) { const result = str.split(',') console.log(result) } else { console.log('The variable has a null value') }
The code for this article is available on GitHub

We explicitly check that the variable doesn't store a null value.

If the variable doesn't store a null value, the if block runs, otherwise, the else block runs.

# Providing a fallback value if the variable stores null

You can use the logical OR (||) operator to provide a fallback value of an empty string if the variable stores a null value.

index.js
const str = null; const result = (str || '').split(','); console.log(result); // ๐Ÿ‘‰๏ธ ['']

The logical OR (||) operator returns the value to the right if the value to the left is falsy (e.g. null).

However, note that the split() method will return an array containing an empty string in this case.

If the separator is not contained in the string, the split() method returns a single element array containing the entire string.

index.js
const str = null; const result = (str || 'abc').split(','); console.log(result); // ๐Ÿ‘‰๏ธ [ 'abc' ]

# Use the ternary operator to solve the error

You can also use the ternary operator to solve the error.

index.js
const str = null; const result = typeof str === 'string' ? str.split(',') : []; console.log(result); // ๐Ÿ‘‰๏ธ []
The code for this article is available on GitHub

The ternary operator is very similar to an if/else statement.

If the expression before the question mark evaluates to a truthy value, the value to the left of the colon is returned, otherwise the value to the right of the colon is returned.

If the value stored in the str variable is falsy (e.g. null), we return an empty array, otherwise, we return the result of 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.

Copyright ยฉ 2024 Borislav Hadzhiev