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

Functions and Arrays Issue

This is from one of the examples the instructor works through. I am looking at the source code and I am having some trouble understanding how the javascript works

The part I am having understanding specifically from the code below:

function print(message) {
  document.write(message);
}

How is the print function writing the ordered list to the document? The print(message) function is never called, so I don't understand how it is being written to the document.

var playList = [
  'I Did It My Way',
  'Respect',
  'Imagine',
  'Born to Run',
  'Louie Louie',
  'Maybellene'
];

function print(message) {
  document.write(message);
}

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

I created a codepen as well here http://codepen.io/anon/pen/xbYXqb

2 Answers

The print function is called on the last line of the printList function. The message part of print(message) is a parameter that is replaced with what you actually want to print. If you called the function print("Hello World!") it would print Hello World! to the screen.

Thanks Colin Marshall my other questions is in regards to 'list' in the following function. Why are we able to use things like list.length and list[i]? I thought we needed to refer to the name of the array for instance playList.length or playList[i]?

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

Your 2nd question is very similar to the first one.

In the function printList(list), the list parameter is like a placeholder. When you actually call the function, you replace list with a list that you want to use in the function.

On the last line when the function is called, you run playList through the printList function. So then when it goes through the function and it runs methods like list[i] and list.length, it is really doing playList[i] and playList.length because you put playList in as the parameter when you called the function.