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:
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.