Home > Software engineering >  Why does the following code cause an infinite loop ? And how to fix the problem
Why does the following code cause an infinite loop ? And how to fix the problem

Time:11-28

let index = 10;
let jump = 2;

for (;;) {
  // Write Your Code Here
     let i = index;
     console.log(i);
     i -= jump;
     if (i === jump) {
         break;
     }
 }

I think that I know the logic of the code, but I don't understand why it does loop infinitely

CodePudding user response:

maybe the following code fixes the problem.

let index = 10;
let jump = 2;
let i = index;

for (;;) {
  // Write Your Code Here
     
     console.log(i);
     i -= jump;
     if (i === jump) {
         break;
         console.log('broken...')
     }
 }

The reason is variable i is being refreshed with static index value 10 every time it loops. Hence it never breaks.

CodePudding user response:

You are assigning 10 to i for each iteration of the loop so i will never be equal jump(2)

Possible Fix


let index = 10;
let jump = 2;
let i = index;

for (;;) {
  // Write Your Code Here
     console.log(i);
     i -= jump;
     if (i === jump) {
         break;
     }
 }

OR

let index = 10;
let jump = 2;

for (;;) {
  // Write Your Code Here
     console.log(i);
     index -= jump;
     if (index === jump) {
         break;
     }
 }

CodePudding user response:

Consider:

    index = 9 (any odd number);
    jump = 2 (any even number);
    i -= jump; //i will be odd all the time;

So "i" will be an odd number; And "jump" is an even number;

    if (i === jump) //odd === even: never match
  • Related