How to Fix Cannot read property ‘replace’ of Undefined in JavaScript

Typeerror: cannot read property ‘replace’ of undefined: In this article, let us see how to fix the Cannot read property 'replace' of Undefined error in JavaScript

Fixing Cannot read property ‘replace’ of Undefined Error in JavaScript

Let us see the examples to know how this error occurs and try to fix them.

1) Calling the replace() function on an undefined String

When calling the replace() function on a variable that stores an undefined value, the error “Cannot read property ‘replace’ of undefined” occurs. To fix the problem, only use the replace function on data types that implement it, such as strings.

index.js:

// Give the string as static input and store it in a variable.
const gvn_str = undefined;

// Apply replace function on the given string to replace 'hello'
// with 'btechgeeks'
// Here we get TypeError: Cannot read property 'replace' of undefined
// error since the string is undefined
gvn_str.replace('hello', 'btechgeeks');

Output:

gvn_str.replace('hello', 'btechgeeks');
^

TypeError: Cannot read property 'replace' of undefined
at Object.<anonymous> (/tmp/toemEjan2d.js:8:9)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

We received the error because we used the replace() method on an undefined value.

2)Reading an Array at an Invalid Index

Another common source of the error is trying to read an array at an invalid index(which does not exist) and then invoking the replace() method.

index.js:

// Give the string as static input and store it in a variable.
const gvn_arry = [];

// Apply replace() function on the first element of the given array as array index starts with 0
// to replace 'hello' with 'btechgeeks'
// Here we get TypeError: Cannot read property 'replace' of undefined
// error since the given array is empty(undefined)
gvn_arry[0].replace('hello', 'btechgeeks');

// we can alse use optional chaining (.) to replace
const rslt = gvn_arry[0].replace('hello', 'btechgeeks');

Output:

gvn_arry[0].replace('hello', 'btechgeeks');
^

TypeError: Cannot read property 'replace' of undefined
at Object.<anonymous> (/tmp/toemEjan2d.js:8:13)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

We can fix Cannot read property 'replace' of Undefined error in JavaScript using the below code

// Take a variable and initilaize its value with undefined
const demo = undefined;
// ✅ Method #1
// Initialize the above variable to empty string
const gvn_str = demo || '';
// ✅ Method #2
// replace hello with btechgeeks using optional chaining(.) and
// replace() function and store it in a variable
const rslt = gvn_str.replace('hello', 'btechgeeks');
console.log(rslt); 

// ✅ Method #3 check if the above result is not empty/undefined using the if conditional statement
if (gvn_str) {
  // If the result is not undefined then replace the hello with btechgeeks using optional chaining and replace function and    // store it in some variable
  const rslt = gvn_str.replace('hello', 'btechgeeks');
}

// ✅ Method #4: Check if the type of the above variable gvn_str is a string using the typeof property
if (typeof gvn_str === 'string') {
    // If it is true, then replace hello with btechgeeks
  const rslt = gvn_str.replace('hello', 'btechgeeks');
}

// ✅ Method #5:  Give the fallback in place
const rslt = (gvn_str || '').replace('hello', 'btechgeeks');

Explanation:

Method #1 in code:

If the value to the left is false (example: undefined), we used the logical OR (||) operator to give a fallback value.

The logical OR operator returns the value to the right if the value to the left is falsy.

Method #2 in code:

The above example explains how to short-circuit instead of throwing an error by using the optional chaining (.) operator.

The optional chaining (?.) operator short-circuits if the value stored in the str variable is undefined or null, returning 
undefined.

Method #3 in code:

The following example verifies that the value saved in the str variable is true. Undefined does not satisfy the criteria because it is a false value.

Method #4 in code:

Before using the replace() method, the fourth example verifies if the value is of the string type.

Method #5 in code:

The final example, right before running the replace method, uses the logical OR (||) operator to provide a fallback.

When working with DOM elements and getting the “Cannot read property’replace’ of undefined” error, make sure:

  • The DOM contains the element you’re working with.
  • After all of the HTML components have been declared, you’ll place the JS script tag at the bottom of the body.