Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
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?

about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

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);
}

about 4 years ago · Santiago Gelvez Report

0

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);
}

about 4 years ago · Santiago Gelvez Report

0

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);
}
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!