How To Display Names Of Undefined JSON Calls

Hello

I’m struggling to work out how to display the name of any account where the status is undefined.

Can anyone give me a hint please?

http://codepen.io/jameswinfield/pen/Gqdkvg

I’ve tried various ways and always just end up with undefined in the output.

Please excuse the exceptionally basic styling!

Thanks
James

The problem lies in the use of channels[i] to display the channel name when the stream is undefined

In Javascript, the variable’s scope is function and not code block (part inside curly braces) so the for loop does not create a scope. This means that once you loop (that initiates the ajax calls) is complete the value of i will be channels.length.

So when the ajax calls complete and execute their callbacks, when you write channels[i] it is looking out of the array bounds.

You need to either create a new closure to capture the i value, or use let in you loop to define the i which creates new scope.

for (let i=0; i<channels.length; i++) { ... }

for chrome you might want to add "use strict"; in your function to allow the use of let.

For more info read

Thanks for that, and the explanation. I read about let the other day - closures I still haven’t got my head around yet so I will use let.

There are number of ways you could do this.

You could do something simple like the below if youre anticipating an undefined result
game = data.stream.channel.status || "I dont think this account exists";

Of course if the stream property is undefined you could user ternary operators:
game = data.stream ? data.stream.channel.status : "I dont think this account exists";

I have a similar problem now trying to use the logos on offline streams! Hmmm

https://codepen.io/jameswinfield/pen/OXwwkb?editors=1111