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

Function? VAR and LET in Arrays for Loops.

Hallo!

May sound like a silly question but JS is getting on my nerves.. I have literally spent 2h on this video... anyway, why does he uses a function? is it a good practise to include a function on 'for loops arrays'?

Also, I thought using 'LET' was a better practise than using 'VAR', and it was my first option, however when I checked it out, the console came up with an error.

Mine looks a bit different from the teacher's, but I have included this here in case someone can check it and provides some feedback :) as I don't want to assume is it's correct, just because ''it works''.

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

var htmlList = "<ol>";
for (var i = 0; i <= playList.length; i += 1 ) {
    htmlList += `<li>  ${playList[i]} </li>`;

}  htmlList += '</ol>' ;

document.write(htmlList)

1 Answer

Steven Parker
Steven Parker
231,275 Points

This should work equally well with "var" or "let", but the one issue i see is that the loop runs one time too many:

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

Changing the comparison limits the loop to the existing array items.