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');


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.

Subscribe to Coding Beauty Newsletter

Gain useful insights and advance your web development knowledge with weekly tips and tutorials from Coding Beauty. Over 2,000 developers subscribe.

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'


If the variable is not nullish but doesn’t have a replace() method, you’ll get a different kind of error:

const obj = {};

// TypeError: obj.replace is not a function
const result = obj.replace('old', 'new');


11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *