Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

do-while loop is not behaving as expected

Feel dumb, but having coded for 10+ years, haven’t used a do-while loop in the last 9. For the life of me, I cannot figure out why this is returning 1 instead of

 const getNextEventCountTest = () => {

        
        let sum = 0;
        let q = 0;

        do {
            sum = sum + 0.5
        }
        while (sum < 4){
         
            q = q + 1;
        }

        return q;
  };

do-while is a good here, since I want to always run the first code block but only conditionally increment q.

but this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

console.log(getNextEventCountTest()); => 1

feeling dumb but dunno lol.

whereas this has the right behavior:

const getNextEventCountTest = () => {
  
        let sum = 0;
        let q = 0;

        // this is desired behavior:
        while (sum < 4){
            sum = sum + 0.5
            if(sum < 4){
               q = q + 1;
            }
        }

        return q;
  };

>Solution :

This is because your code executes like do { ... } while(condition); { ... }. Notice the added semicolon – the second {} block executes once.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading