Cannot read properties of undefined (reading 'replace')

avatar
Borislav Hadzhiev

Last updated: Mar 3, 2024
4 min

banner

# Cannot read properties of undefined (reading 'replace')

The "Cannot read properties of undefined (reading 'replace')" error occurs when calling the replace() method on a variable that stores an undefined value.

To solve the error, make sure to only call the replace method on data types that implement it, e.g. strings.

cannot read property replace of undefined

Here is an example of how the error occurs.

index.js
const str = undefined; // ⛔️️ TypeError: Cannot read properties of undefined (reading 'replace') str.replace('test', 'replacement');

cannot read properties of undefined reading replace

We called the replace() method on an undefined value, so the error occurred.

Another common cause of the error is accessing an array at an index that doesn't exist and calling the replace() method.

index.js
const arr = []; // ⛔️️ Cannot read properties of undefined (reading 'replace') arr[0].replace('test', 'replacement'); // ✅ Use optional chaining (?.) instead const result = arr[0]?.replace('test', 'replacement');
The code for this article is available on GitHub

# Initialize the variable to an empty string

One way to solve the error is to use the logical OR (||) operator to initialize the variable to an empty string.

index.js
const someVar = undefined; const str = someVar || ''; // 👉️ "" const result = str.replace('test', 'replacement'); console.log(result); // 👉️ ""

initialize variable to empty string

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

You can also provide a fallback of an empty string right before calling the String.replace() method.

index.js
const str = undefined; const result = (str || '').replace('test', 'replacement'); console.log(result); // 👉️ ""

provide fallback right before calling string replace

If the str variable stores a falsy value (e.g. undefined), the expression calls the replace() method on an empty string.

# 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?.replace('test', 'replacement') || ''; console.log(result); // 👉️ ""

using optional chaining operator 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).

# Using an if statement to solve the error

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

index.js
const str = undefined; if (typeof str === 'string') { const result = str.replace('test', 'replacement'); console.log(result); } else { // 👇️ this runs console.log('The variable does NOT store a string'); }

using if statement to solve the error

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.

# 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.replace('test', 'replacement') : ''; console.log(result); // 👉️ ""

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 string, otherwise, we return the result of calling the replace method.

# 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 how the error occurs when working with arrays.

index.js
const arr = []; // ⛔️ TypeError: Cannot read properties of undefined (reading 'replace') arr[0].replace('test', 'replacement');

To resolve 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].replace('test', 'replacement') : ''; console.log(result); // 👉️ ""

Before calling the replace 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 to empty string last = ''; // ✅ Initialize from parameters constructor(first) { this.first = first; } replaceFirst() { return this.first.replace('test', 'replacement'); } replaceLast() { return this.last.replace('test', 'replacement'); } } const p1 = new Person('John'); p1.replaceFirst(); p1.replaceLast();
The code for this article is available on GitHub

We initialized the values of the first and last class properties. Had we not done that, we would get the error when trying to access the properties.

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

# Solve the error when working with DOM elements

If you're getting the error when working with DOM elements, make sure:

  • the element you're working with exists in the DOM.
  • you're inserting the JS script tag at the bottom of the body, after all of the HTML elements have been declared.

# Conclusion

The "Cannot read properties of undefined (reading 'replace')" error occurs when calling the replace() method on an undefined value.

To solve the error, provide a fallback for the value if it's equal to undefined and conditionally check that it stores the correct data type before calling the 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.