CodeNewbie Community 🌱

Will
Will

Posted on

How do you know when to use different types of loops? (i.e. for...of vs. for vs. while)

Hey all!

Recently, I've been studying loops in JavaScript and was wondering if more experienced developers could give some examples of when to best use each of them. For example, when should I use a for loop vs. a while loop or vice versa?

Thanks!

Top comments (3)

Collapse
 
terabytetiger profile image
Tyler V. (he/him)

The way I've always decided is that for loops are for "known" lengths and while loops are for "unknown" lengths.

To break this down further - if you have an array and need to loop over each element of the array, you can use for (item of array). We know it's going to be a for loop because we want to hit each element 1 time over the course of our loop.

If we wanted to add items to an array until the length of the array was 100 or more items, we could use while (array.length < 100) - the big thing here is that we don't know how long our array will be when it starts.

Does that clarify things?

Collapse
 
will_i_am_a_dev profile image
Will

It does, thanks so much!

Collapse
 
larrymartin1job profile image
Larry Martin

For simple iterations over arrays for...of is concise while for offers more control over looping conditions. While is handy for indefinite loops where the exit condition isnt initially known.
Flight School in North Las Vegas NV