While or For Loop | Which to use?

Aisha Wahab O.
2 min readApr 3, 2024

We should understand that every loop has its advantage as well as drawback. They can be used in their own respective special cases.

For instance, when we know the starting and ending values, and also iterations, the For Loop’s the best.

If let’s say, we want to print all the even numbers between one to one hundred or want to print all the numbers divisible by 4 between 5 to 500, our For Loop’s the go to. Because we know the starting values , the end values as well as the condition.

For example, let’s print all values divisible by 3 from 1 to 100.

for(let i=1; i<=100; i++)

{

if(i%3===0)
console.log(i);

}

As for While Loop, it’s better when we don’t know the starting point and ending point, but we know the condition.

Example:

let num = 564782

while num(>0)

{
console.log(num%10);
num= parseInt (num/10)

}

Although, some programmers opine one of the loops is better than the other, but, depending on the cases, these loops have their distinct functions and applications.

In essence, while the For Loops are used for definite loops when the number of iterations is known, and when we know exactly how many times the loop will be repeated, While Loops on the other hand , are preferred when the number of iterations isn’t known . The While Loop will continue to run infinite number of times until the condition is met.

--

--