Ryan
Ryan

Reputation: 199

While Loop Still Triggering When not Supposed too

Doing a while loop in JavaScript but it's displaying 120 when usernum < 50 but calculating when usernum is 60.

var userNum = 4; // Code will be tested with values: 4, 10 and 60
/* Your solution goes here */
do {
  userNum = 2 * userNum;
  console.log(userNum);
}
while (userNum < 50);

CORRECT Testing displayed output with userNum = 4 Yours 8 16 32 64

CORRECT Testing displayed output with userNum = 10 Yours 20 40 80

INCORRECT Testing displayed output with userNum = 60 Yours and expected differ. See highlights below. Yours 120 Expected Expected no output

Upvotes: 0

Views: 47

Answers (1)

5eeker
5eeker

Reputation: 1027

A do while loop runs the code once, and then tests the condition, if it is false, it stops the execution. You should use while or for loop.

while(userNum < 50){
userNum = 2 * userNum;
console.log(userNum);
}

while -> check condition, if true run code, else stop

for -> check condition, if true run code (basically shorter version of while)

do while -> run loop, check condition, if true run again or exit;

Upvotes: 3

Related Questions