1

I tried to deconstruct an array in a recursive method. Below is a simplefied example. Everything is working just fine.

function createNode(index, node) {
    let next = node+ 1
    if (next < 100) {
        for (let i=0; i < 5; i++) {
            [index, next] = createNode(index, next)
        }
    }
    return [index, next]
}
createNode(0, 0)

However when I add console.log to the for loop it crashes.

 for (let i=0; i < 5; i++) {
     console.log(next)
     [index, next] = createNode(index, next)
 }

Uncaught TypeError: Cannot set property '99' of undefined

The problem isn't getting around it. I just want to understand and know what is causing it. I've been searching for a while now and to be honest, I have no idea yet.

  • 1
    This reminds me of the [Great Semicolon Debacle of 2012](https://github.com/twbs/bootstrap/issues/3057). – Andy Dec 08 '18 at 16:30
  • Please add semicolons and Eslint or any other linter on your project! you will avoid having this kind of issues and problems in the future. – Miguel Angel Dec 10 '18 at 23:10

1 Answers1

0

You omitted the semicolon

See https://stackoverflow.com/a/2846298/4023734

This is the primary reason your code is not working. Usually you can get away with that because JavaScript automatically inserts the semicolons for you.

But in this case the sentence is followed by another which starts with the character [

so,

console.log(next)
[index, next] = createNode(index, next)

is actually the same as

console.log(next)[index, next] = createNode(index, next)

and javascript will evaluate console.log(next) (which returns undefined) and then try to get [index, next] of it. since the expression inside [] index, next is a comma separated expression it evaluates to the last expression, so it effectively the same as just next

the reason the error mentions 99 is because when evaluating this:

console.log(next)[index, next] = createNode(index, next)

the right side needs to be evaluated before the assignment is done, and since it has a recursive call, only after the terminal case will the first assignment be done (after next < 100 evaluates to false)

so when it errors it is trying to evaluate:

undefined[99] = [0, 100]
Tiago Coelho
  • 5,023
  • 10
  • 17