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

ian izaguirre
ian izaguirre
3,220 Points

Confused about the JS best practices with Length property in the For Loop?

function printList ( list ) {

var listHTML = '<ol>'; 

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

listHTML += '</ol>'; 

}

Before watching this video I had come across this link (https://www.w3.org/wiki/JavaScript_best_practices)

And then I watched this video which seems to go against what is written in Section 12 "Optimize Loops" .

hmm so I am a little lost as to which practice I should stick too. Since I am just learning I am not 100 percent sure, but should I follow the recommendation on the link and Always declare the array length property in a separate variable instead of directly in the For loop to save on memory? Just asking since he did not do it in the video ?

1 Answer

Steven Parker
Steven Parker
231,275 Points

I found it amusing that other examples in the same article (such as the one for #8 - Modularize) did not follow this "best practice".

I'm not sure I'd call this a "best practice" but I would recommend keeping it in mind for optimizing compute-heavy tasks. I did some benchmark tests and found that it can reduce running time by 5-13%, depending on the array size.

ian izaguirre
ian izaguirre
3,220 Points

lol that is ironic, good eye! and thanks for testing the results.

ian izaguirre
ian izaguirre
3,220 Points

@Steven Parker

Hi, I have a random question. I was wondering if your a mod, because I always see you giving awesome answers to peoples questions :-) ? Is there a way I could private message you through tree house or does tree house not have that feature ?

Steven Parker
Steven Parker
231,275 Points

No, I'm not a mod though I was invited to be one once. I accepted when I realized it would allow me to help more people (and provide better quality assistance) but I was told that new mods were not being added anymore.

You can easily spot a mod by the distinctive orange ring around their avatar, and when you hover your mouse pointer over the avatar the pop-up will say "Treehouse Moderator" beneath their name.

And I'm not aware of any private message feature on the Treehouse system.