function pow(x,n) {
let result = x;
for (let i = 1; i < n; i++) {
result *= x;
}
return result;
}
pow(5,2);
pow(5,3);
if (n < 1) {
alert(`Power ${n} is not supported, use a positive integer.`);
} else {
alert( pow(x,n) );
}
Hello,
Back again with another question… Haha…
Here we have a piece of code that exponentiates the two variables “x” and “n”.
I understand the code for the most part, until it gets to the for loop inside the function.
I have been testing the code with (5,2);
and (5,3);
If result = x;
Why doesn’t the code run 25 x 25 for the 3rd iteration? Doesn’t result *= x;
change the x
variable?
Also, why is if (n < 1)
not inside the pow(x,n)
function? How does the if…else statement work with the function if it is not inside it? Is that because functions can see outer variables?
Thanks a lot for helping me with my last question.
Hopefully this will be the last one.
Much appreciated,
Peter