Question about do...while loop

My code seems to be causing an infinite loop and I can’t figure out why. Here it is:

const input = document.querySelector('input');

const btn = document.querySelector('button');

const para = document.querySelector('p');

btn.addEventListener('click', () => {
  para.textContent = 'Output: ';
  const num = input.value;
  input.value = '';
  input.focus();
  let i = 1;
  do {
    let sqRoot = Math.sqrt(i);
    if(Math.floor(sqRoot) !== sqRoot) {
      continue;
    }
    para.textContent += `${i} `;
    i++;
  } while(i <= num);
}); 

Why would this code cause an infinite loop?

Hi @church_craig

The problem is the use of continue. It stops the current round of the loop and starts the next one. In this case i++ won’t get called and the loop’s next round will have the same value for i.
A solution would be to chance the condition to Math.floor(sqRoot) === sqRoot and add the text inside the if statement. This will always call i++ and if we have a square number it will also output it.

See you,
Michael

This post is very bizarre.

What does it mean?

I tried what you suggested and it worked. As you may be aware I took the code from the Looping code article on MDN and tried to apply a do...while loop to it. The original code is used to display the use of the continue statement. Here is the original code:

const para = document.querySelector('p');
const input = document.querySelector('input');
const btn = document.querySelector('button');

btn.addEventListener('click', () => {
  para.textContent = 'Output: ';
  const num = input.value;
  input.value = '';
  input.focus();
  for (let i = 1; i <= num; i++) {
    let sqRoot = Math.sqrt(i);
    if (Math.floor(sqRoot) !== sqRoot) {
      continue;
    }
    para.textContent += `${i} `;
  }
});

The article states that the for, while and do...while loops are largely interchangeable. So my question is can the code be rewritten with a do while loop and include if(Math.floor(sqRoot) !== sqRoot) {continue}, or do you have to remove the continue statement and rewrite the code with if(Math.floor(sqRoot) === sqRoot)?

I think the intention behind “largely interchangeable” is to say “with small changes”. Using my changes from above seems to be the clearest change.
That being said, if you want to keep the if statement the same, you could do the following:

  • Change the initial value of i to 0
  • Move i++ to the start of the loop
  • Change the loop condition to lesser than
btn.addEventListener('click', () => {
  para.textContent = 'Output: ';
  const num = input.value;
  input.value = '';
  input.focus();
  let i = 0;
  do {
    i++;
    let sqRoot = Math.sqrt(i);
    if(Math.floor(sqRoot) !== sqRoot) {
      continue;
    }
    para.textContent += `${i} `;
    
  } while(i < num);
});