Reputation: 39
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>
Upvotes: 1
Views: 786
Reputation: 7665
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)
Upvotes: 1