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

Elena Paraschiv
Elena Paraschiv
9,938 Points

What is the purpose of function print(message)?

Can someone please explain this snippet of code and how is it used in the bigger picture. I dont figure out why is this added to the code?

function print(message) {
  document.write(message);
}
Elena Paraschiv
Elena Paraschiv
9,938 Points
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);

2 Answers

Grace Kelly
Grace Kelly
33,990 Points

Hi Elena, the purpose of this print function is that it removes the need to write document.write() everytime you want to output something to the screen, for example:

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

print("Hello, World!"); //outputs Hello, World! to the screen

var name = "Mike";

print(name); //outputs Mike to the screen

In your example above it is used in print(listHTML). This will output the contents of the listHTML variable to the screen.

Hope that helps!!

William Ruiz
William Ruiz
10,027 Points

But document.write() isn't that long, and it is 1 line vs 3 lines. So is it intended to build a positive habit in newbies like me? In case in the future longer blocks can be called with a single function? I just don't know if I see its full efficiency at the moment because I know, say, Python just uses print() but ES6 doesn't have this recommendation?