1

I cannot figure out why this is returning 1 instead of 7.

 const getNextEventCountTest = () => {

        
        let sum = 0;
        let q = 0;

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

        return q;
  };

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

But this:

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

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;
  };
4
  • 2
    Perhaps because your code executes like do { ... } while(condition); { ... }. Notice the added semicolon Commented Nov 12, 2022 at 2:33
  • ah yes, that's correct Commented Nov 12, 2022 at 2:35
  • 1
    The language perils of optional semi-colons. It would be interesting to see what a good linter says about this code. Commented Nov 12, 2022 at 2:39
  • well it's been so long since I used a do-while lol, but the frankenstein construct I made up in OP has some value even though semantically it's a mess. Coincidentally intellij was forcing the braces after the while statement on a newline and I couldn't figure out why, now I know. Commented Nov 12, 2022 at 2:42

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

Your syntax is wrong regarding do while loop. Use this instead

do {
  //Your code that is to be executed
}
while(/* condition */);

I have improved the code for you;

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

  // works only when sum and q are defined as an integer
  do{
     sum += 0.5
     if(sum < 4) q++;
  }
  while(sum < 4)
  return q;
}

Then, it will work as expected. Bye, have a great day!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.