Home > Software design >  Why is this for loop looping infinitely?
Why is this for loop looping infinitely?

Time:07-17

let n = 5;

for (let a = 1, b = Math.pow(2, a); b <= n; a  ) {
   console.log(b);
}

I don't understand why b doesn't increase as a increases. Do I have to somehow pass a to b again?

If there's no way to make this loop work this way, can someone tell me how I could rewrite it so it works?

CodePudding user response:

Once b is initialized, your code never changes it, so the loop condition is always true.

You could use

let n = 5;

for (b = 2; b <= n; b*=2) {
   console.log(b);
}

CodePudding user response:

b is of value type not of reference type. So updating a will not automatically update value of b

You have to update it manually

for (let a = 1,b =Math.pow(2,a); b <= n; a  ,b=Math.pow(2,a)) {
   console.log(a);
}

CodePudding user response:

Yes, you do have to pass a to b again in order to get your code to work, as b does not change as the loop progresses. Here is how you would rewrite your code to give it the functionality you want:

let n = 5;
let b;
for (let a = 1; b <= n; a  ) {
   b = Math.pow(2, a);
   console.log(b);
}

CodePudding user response:

You can get it working like below. Your case is more likely fit for while or do while loop.

let n = 5;
let a = 1;
   
while(powToA(a)<=n) {
   console.log(powToA(a));
   a  ;
}


function powToA(a) {
  return Math.pow(2, a);
}

  • Related