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

I wrote the program differently and it ran, is there any advantage to the way that he wrote it?

Here is it is from the beginning 1) Didn't see the need of the function at the top of his that just does document.write 2) For some reason the way mine came out, the function is contained in the loop. (his way was the loop inside of the function) .....

var playList = [
  'I Did It My Way',
  'Respect',
  'Imagine',
  'Born to Run',
  'Louie Louie',
  'Maybellene',
  'Hit me baby one more time'
];

//This varialbe html opens the ordered list
//by the end of the array, it will contantonate to include all of in information in the array into an orderd list!
var List = "<ol>";

for (i = 0; i < playList.length ; i += 1) {

  function listAssemble() {
List += '<li>' + playList[i] + '</li>';
  }

  listAssemble();

}

// closes the ordered list
List += '</ol>'

document.write(List);

I updated your question with proper code formatting. Please see the Markdown Cheatsheet for instructions on how to post code to the forums. Thanks!

Colin Marshall How do you update someone else`s code?

Gunhoo Yoon I can edit your posts because I am a Treehouse Community moderator.

2 Answers

  1. Writing document.write() as a separate function is not necessary but it helps when you call document.write() many times and you want to give it more capability. So it's your choice in this case.

  2. Did you define listAssemble function inside a loop just to get access to i variable? That is very ineffective because you are defining same function multiple times whenever loop iterates. Why not use parameters to fill that role? Also, in your case you don't even need it because you can simply write

    List += '<li>' + playList[i] + '</li>';

You should reason about your code every time as they represent your decision.

Hey Aaron,

I don't know who you're referring to when you say 'he'... but the code you posted above is kind of the the poster-child for bad practices in JavaScript. It's okay though; we all start somewhere :)

So for starters, we don't define functions inside of loops. If you give it some thought, you'll realize that a loop just repeats a piece of code over and over — so you're basically defining the function (as well as calling it ) every time the loop restarts. There's some more minor errors but this is probably the biggest one you should be aware of.