Search code examples
javascripttypescriptasynchronousiteratorclosures

understanding local variables, closures and iterators


I have a code block like the below, it's a sync function. I want to collect in reply info on items.

However reply is always returning as the empty array even when I have items. When I check in the debugger, the info shows reply as a closure variable, not a local. I'm wondering if there's something going on with hoisting here that I don't understand?

enter image description here

  invStatus() {
    let reply: string[] = []
    Logger.log('player.status.items:', this.items)
    if (!this.items.length) {
      reply.push('nothing')
    } else this.items.map(item => {
      Logger.log('item', item)
      reply.push[`- ${item.name}`]
    })
    Logger.log('player.status.reply:', reply)
    return reply
  }

hmm this is typescript also, I wonder if the transpiler behavior is subtly different?

I probably should use a .forEach here since I'm not capturing the return of the map or transforming things but I understand that has the same iterator behavior. The only other thing would be to go with a for x of which is more reliable, but I'd like to understand the issue here!


Solution

  • I think you have made a syntax error.

    Observe this line:

    reply.push[`- ${item.name}`]
    

    Here, instead of parantheses, you have used square brackets.

    Corrected code would be,

    reply.push(`- ${item.name}`)
    

    I know javascript but not typescript but I believe this must be the cause of the issue.