1

I'm trying to pass two arguments in a function that has String.prototype.slice(), but the console keeps on returning this error:

Uncaught TypeError: Cannot read property 'slice' of undefined".

Aren't the arguments supposed to be passed?

const testText = '<p style='color: red;'>This is a test</p>'
const testParagraph = document.getElementById('test')

const message = (paragraph, originText) => {
  let i = 0,
    text, isTag
  const speed = 50
  text = originText.slice(0, ++i)
  if (text === originText) return
  paragraph.innerHTML = text
  const char = text.slice(-1)
  if (char === '<') isTag = true
  if (char === '>') isTag = false
  if (isTag) return message()
  setTimeout(message, speed)
}

message(testParagraph, testText)
<div id="test"></div>

2
  • 1
    I made you a snippet. Please first fix the error you get when you nest the same kind of quotes const testText = '<p style='color: red;'>This is a test</p>' Commented Jan 25, 2019 at 15:47
  • 1
    setTimeout(message, speed) does not pass any text so second time around the parameters are empty Commented Jan 25, 2019 at 15:50

1 Answer 1

1

There are two places where a recursive call of message function may happen:

if (isTag) return message()
setTimeout(message, speed)

In both cases message function is called without arguments. Due to this paragraph are originText parameters are associated with undefined value. Then it tries to call .slice on undefined which raises the error.

You need to pass arguments to a recursive call, since it (like a regular function invocation) creates a new execution context with it's one lexical environment.

if (isTag) return message(arg1, arg2)
setTimeout(message.bind(null, arg1, arg2), speed)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I'm now facing a RangeError: Maximum call stack size exceeded error but I'll see what I can do
You are welcome! "Maximum call stack size exceeded" error usually happens due to reaching the limit of recursion depth. Make sure that you either have a correct exit condition defined within the recursive function or (if you need to run the function constantly) each recursive call is wrapped in setTimeout (in this way, next recursive call will happen outside of the current event loop iteration).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.