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 Using For Loops with Arrays

Natalia Karolinskaya
Natalia Karolinskaya
9,367 Points

I don't understand two things in this exaple

https://w.trhou.se/rxigpql9yw

  1. listHTML += '<li>' + list[i] + '</li>';

Initial value of i is 0, so ho come the list starts with number 1?

  1. I don't see where in the function printList we instruct it to print the playList? I mean we say print playList in the end, but that is note the function code anymore.

Thanks for your help!

2 Answers

An arrays index begins at 0 so that is why the inital value of i = 0.

var playList = [
  'I Did It My Way', // playList[0]
  'Respect', // playList[1]
  'Imagine', // playList[2]
  'Born to Run', // playList[3]
  'Louie Louie', // playList[4]
  'Maybellene' // playList[5]
];

So the printList function cycles through the playlist array and prints them out.

function printList( list ) { // list = playList[]

  var listHTML = '<ol>';

//This for loop prints out each item in the playList array
  for (var i = 0; i < list.length; i += 1) {
    listHTML += '<li>' + list[i] + '</li>';
  }
  listHTML += '</ol>';
  print(listHTML);
}
printList(playList); // playList is called as an argument in the printList function

alright, I have the same questions as noted above...and I will raise you this one. WHY does list = playList. That is not mentioned thus far that I can see. If it is an understood shortcut of some sort, I would have been less confused if that were mentioned in the lesson.

list = playList because you call the printList() function with playList as the argument.

printList(playList); 

The parameter list could be called anything and It would still equal to playList[]. View Below

function printList( k ) { // k = playList[]

  var listHTML = '<ol>';

//This for loop prints out each item in the playList array
  for (var i = 0; i < k.length; i += 1) {
    listHTML += '<li>' + k[i] + '</li>';
  }
  listHTML += '</ol>';
  print(listHTML);
}
printList(playList); // playList is called as an argument in the printList function

I hope this helps. Feel free to ask me another other questions you may have.