TypeError problem

function myReplace(str, before, after) {
  let index=str.indexOf(before)
  if(str[index]===str[index].toUpperCase()){
    after=after.charAt(0).toUpperCase()+after.slice(1)
  }
  console.log(after)
}

myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

The output shows typeError
TypeError: Cannot read properties of undefined (reading ‘toUpperCase’)

Can someone explain why this is happening?

The string “jumped” is not found in “A quick brown fox umped over the lazy dog” so index is -1, so str[index] is undefined.

1 Like

even if its ‘jumped’, still same error shows up if i console.log it

What this error is saying is, “We are trying read a property/method called ‘toUpperCase’ but the place we are looking is a variable that evaluates to ‘undefined’. That is illegal.”

That means that either str[index] is undefined or after.charAt(0) is.

I would put in some log statements like this:

function myReplace(str, before, after) {
  let index=str.indexOf(before)
  console.log('index', index)
  console.log('str[index]', str[index]) 
  console.log('after.charAt(0)', after.charAt(0))
  if(str[index]===str[index].toUpperCase()){
    after=after.charAt(0).toUpperCase()+after.slice(1)
  }
  console.log(after)
}

myReplace("A quick brown fox umped over the lazy dog", "jumped", "leaped");

This is what @colinthornton was talking about. If I correct the text, I don’t get the error.

And please don’t make changes to code after they’ve been discussed - it makes it confusing to follow the thread.

1 Like