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