Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is this for loop looping infinitely?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading