2

When I'm setting an anonymous callback function on some REST service, I'm getting a very strange behavior where if I simply console.log the result of the REST service, I get the expected payload (an array of Objects). However, when I run a loop over the same array and try get some key's value, I get a error because apparently the item is undefined

...
callback: (result) => {
    console.log(result); // outputs [{text: 'foo'}, {text: 'bar'}]
    for(let item of result){
        console.log(item.text); // error can't read text of undefined
        console.log(item); // HOWEVER... this works... :/
    }
}

Any ideas? There must be some kind of async behavior happening, but I can't figure it out.

Thanks!

7
  • 1
    This isn't a typescript error, this is just JavaScript Commented Jul 7, 2016 at 8:06
  • any idea why I get this error? Thanks Commented Jul 7, 2016 at 8:08
  • Everything seems to work as expected. Are you sure the response is really as in the comment? Commented Jul 7, 2016 at 8:08
  • use item['text'] instead of item.text. It should surely works... Commented Jul 7, 2016 at 8:15
  • Is this your actual code or you simplified it for the question? Have you debugged it using breakpoints? Commented Jul 7, 2016 at 8:18

1 Answer 1

2

You most likely have a malformed array. Here is an example that demonstrates the problem:

// Malformed array
const result = [
    {text: 'foo'},
    {text: 'bar'},
]
result.length = 3;

// Your code
console.log(result); // outputs [{text: 'foo'}, {text: 'bar'}]
for(let item of result){
    console.log(item.text); // error can't read text of undefined
    console.log(item); // HOWEVER... this works... :/
}

Fix

  • Filter out the empty items.

More tips

  • console.log will print an empty line for unreasonable stuff. You might not be seeing that in your debugging
  • Read up on JavaScript array holes
  • Enjoy life 🌹
Sign up to request clarification or add additional context in comments.

1 Comment

this is weird... and does not make much sense

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.