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

Marcel Carey
Marcel Carey
2,890 Points

When using for loops, whats the difference between using .length or just a boolean value

So I have this ex. let numbers = [] for(let i = 0; i < numbers.length; i++){ return doSomething } vs let numbers = [] for(let i = 0; i < 0; i++){ return doSomething }

1 Answer

In case of: for( let i = 0; i < numbers.length; i++) You run the loop as many times as there are values in array numbers[], The part "i < numbers.length" stands for condition to run the loop, if it's true the loops run, if it's false the loop stops. If you use: for(let i = 0; i < 0; i++) and array isn't empty the for loop won't run even once, because before you execute code in {} your condition (i<0) is false and loop ends.

It is a good idea to loop certain numer of times in this case as many times as arguments in numbers[] array.