JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Using For Loops with Arrays

Why we don't use our already existed array(playList), instead of creating a new array(list)?

It gave the same result and It make more sense for me. so the code will be like this: var playList = [ 'I Did It My Way', 'Respect', 'Imagine', 'Born to Run', 'Louie Louie', 'Maybellene' ];

function print(message) { document.write(message); } function printList( playList) { var listHTML = '<ol>'; for (var i = 0; i < playList.length; i += 1) { listHTML += '<li>' + playList[i] + '</li>'; } listHTML += '</ol>'; print(listHTML); } printList(playList);

5 Answers

You're right, we could pass the array to the function when we create it, but in this video, when we create the function printList we aren't passing anything to it at first. list isn't an array it's called a parameter, and it's like a placeholder saying we are going to put something into the function later.

When we call the function printList() at the bottom that's when we tell it we want to use the information stored in the variable playList.

The benefit of using a parameter when we create the function is we can reuse the function on different arrays. We could have an array called playList and another one called movieList and we wouldn't need to rewrite the function. Instead we would call the function twice like this:

printList(playList);
printList(movieList);
Doron Geyer
Doron Geyer
Full Stack JavaScript Techdegree Student 5,039 Points

What is confusing people is the parameter 'list' is just a placeholder which is being used to build the function. so when you call

printList(playList); this calls the function you created printList() and replaces the parameter in parenthesis with your array playlist.

so

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

will then become

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

so it could have been called printList(placeholder); or printList(userArray) instead of printList(list). Using list made it more confusing.

you need a placeholder name to use properties like length in your function. if you left your function as printList(); when you needed to do your for loop, the second bit that checks wouldnt work because you would have

.length which would do nothing

you needed

something.length

Lioz Elinger
Lioz Elinger
4,766 Points

That's what I was about to ask. Maybe someone knows?

That's what been bugging me as well. I hope we get some clear answers for this

maya sophie
maya sophie
5,754 Points

yes, I was thinking the same: how the program is working when first we have 'playList' and then we build a function for 'list' but somehow(and this is what I don't understand) the program applies the function to playList.....