How to Fix the "Cannot Read Property 'replace' of Undefined" Error in JavaScript

Last updated on August 17, 2022
How to Fix the "Cannot Read Property 'replace' of Undefined" Error in JavaScript

Are you experiencing the "cannot read property 'replace' of undefined" error in JavaScript? This error occurs when you attempt to call the replace() method on a variable that has a value of undefined.

const str = undefined;

// TypeError: Cannot read properties of undefined (reading 'replace')
const newStr = str.replace('old', 'new');

console.log(newStr);

To fix the "cannot read property 'replace' of undefined" error, perform an undefined check on the variable before calling the replace() method on it. There are various ways to do this, and we'll cover 4 of them in this article.

1. Use an if Statement

We can use an if statement to check if the variable is truthy before calling the replace() method:

const str = undefined;

let result = undefined;
// Check if truthy
if (str) {
  result = str.replace('old', 'new');
}

console.log(result); // undefined

2. Use Optional Chaining

We can use the optional chaining operator (?.) to return undefined and prevent the method call if the variable is nullish (null or undefined):

const str = undefined;

// Optional chaining
const result = str?.replace('old', 'new');

console.log(result); // undefined

3. Call replace() on a Fallback Value

We can use the nullish coalescing operator (??) to provide a fallback value to call replace() on.

const str = undefined;

const result = (str ?? 'old str').replace('old', 'new');

console.log(result); // 'new str'

The null coalescing operator (??) returns the value to its left if it is not null or undefined. If it is, then ?? returns the value to its right.

console.log(5 ?? 10); // 5
console.log(undefined ?? 10); // 10

4. Use a Fallback Result Instead of Calling replace()

We can combine the optional chaining operator (?.) and the nullish coalescing operator (??) to provide a fallback value to use as the result, instead of performing the replacement.

const str = undefined;

const result = str?.replace('old', 'new') ?? 'no matches';

console.log(result); // 'no matches'

See also