For Loops vs While Loops

What to choose when looping through a collection of elements?

Fay Vera
Aug 17, 2021

For loops are preferable for when you know the amount of times that you will be looping for. When you set for (let i = 0; i < 100; i++) we know that we want the counter i to keep adding on to itself until we reach i < 100 . This scenario is best used when we know the condition we would like for it to stop.

While loops on the other hand, are preferred for when we don’t know the exact amount of times needed to loop through in order to meet the condition we set, which gives us a little more flexibility. We can then do:

let valid = 6;
while(valid < 10)
{valid += 1}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response