Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Two-Dimensional Arrays

Marc Murray
Marc Murray
4,618 Points

Couple of quirks I'm noticing with arrays, they seem to be acting strangely for me.

Just a couple of oddities I have noticed that seem to contradict what the course has shown me so far, just wondering if anyone could clear up the confusion I am having at the moment?

  1. When I use a loop to access items in an array, it seems to always count one further than it should and prints the value 'undefined" for the last item every time. I can fix this using things like (playlist.length - 1); in my loops but it doesn't seem like I should need to.

  2. This function here so far prints both the song title and artist name, which is meant to be the eventual goal of this video, then when I add [0] after [i] like instructed, the console then warns me that songs[i] is undefined. My code is below. NOTE: Figured out the second one, my mistake!

There's probably something ridiculous I am overlooking but the first question in particular has been niggling at me since the beginning of the section on arrays. Thanks to anyone who'll take a look! :)

var playlist = [
['I Did It My Way',' Frank Sinatra'],
['Orangutan Blues', ' Mick Delamere'],
['Strongmen Defenders', ' The Country Clubs Wastrels'],
['Wheres My Weed At', ' Cooncoon']
];

function printSongs(songs) {
    var listHTML = '<ol>';
    for ( var i = 0; i <= songs.length; i += 1) {
        listHTML += '<li>' + songs[i][0] + ' by ' + songs[i][1] + ' </li>';
}
listHTML += '</ol>';
print(listHTML);
}

printSongs(playlist);

1 Answer

LaVaughn Haynes
LaVaughn Haynes
12,397 Points

remove the "=" in your loop

//for ( var i = 0; i <= songs.length; i += 1) {
for ( var i = 0; i < songs.length; i += 1) {

Remember arrays start counting from 0, not 1. Since you are starting with 0 you want to stop before i equals the length of your array. For example, you have for elements so your loop is good for "i is equal to 0, 1, 2, and 3". i equals 4 (the length of your array) is undefined.

Marc Murray
Marc Murray
4,618 Points

Derp, I had this concept yesterday and had since totally forgotten it. Thanks!