DEV Community

Discussion on: Tell me what confuses you the most about JS / TS / React / functional programming and I will write a full length article for you

Collapse
 
dripmarcuz profile image
Otunba💦

Hi Mateusz, I would like to know when the while loops are to be used instead of the for loops. Thanks

Collapse
 
jimmymcbride profile image
Jimmy McBride

For loops loop over something a defined number of times. A while loop is able to run an undefined number of times until a condition is met.

const array = new Array(10);

for (let i = 0; i < array.length; i++) {
  // This will always run 10 times
  console.log(i);
};
function main() {
  let state = false;

  // This will loop a random number of times until that condition is met
  while (!state) {
    const ranNum = generateRandomNumber();
    if (ranNum === 5) {
      state = true;
    }
  }
};