Ashwin Gupta Ashwin Gupta - 8 months ago 38
Javascript Question

Why are my defined strings printing to the console as undefined?

I've written a very simple application that pulls all the tracks off of a spotify playlist. First, it gets the track JSON objects using an AJAX request and puts them in an array called


Next, I iterate through this array, and in each iteration I pull out the strings for the name of the song and the artist for each track. I put these in a concentrated string. This string is then stored in a new array called
. This is done for each track.

is an array that looks something like

"Sympathy for The Devil, The Rolling Stones",
"Come Together, The Beatles",

At this point I have a strange issue. According to chrome's debugger, the array
has all of the correct values inside of it. However, when I attempt to
any element of
I end up with the value 'undefined'. Stranger yet, if I
the expression I use to get the two strings and stitch them it prints the correct value.

Why does this happen and how can I fix it so it can
the correct values

Here is the code that iterates through stored JSON objects, stores them in new array, and prints:

function print() {
for(var x = 0; x < 4; x++) {
for(var n = 0; n < 100; n++) {
try {
//this logs correct
console.log(tracks[x].items[n] + " " + tracks[x].items[n].track.artists[0].name);

//these have correct value
var deb = (tracks[x].items[n] + " " + tracks[x].items[n].track.artists[0].name);
complete[z] = deb;

console.log(deb); //throws no error, prints fine
console.log(complete[z]); //prints undefined

} catch(err) {
//no exception ever thrown

I don't do too much JS, sorry if I'm missing something obvious.


Right after assigning complete[z], you are incrementing z. When printing, you are not accessing complete[z] anymore, but complete[z+1] which is not yet defined. Try moving the incrementation after the console.log command.