ayanda
(ayanda)
September 1, 2020, 9:11am
1
What does the
for (let i = 1; i < n; i++)
in the code below mean?
function pow(x, n) {
let result = x;
for (let i = 1; i < n; i++) {
result *= x;
}
return result;
}
let x = prompt("x?", '');
let n = prompt("n?", '');
if (n < 1) {
alert(`Power ${n} is not supported, use a positive integer`);
} else {
alert( pow(x, n) );
}
@ayanda this means we are looping through some code using a standard for loop.
We are starting with a value of i equal to 1 (let = 1
) .
We continue looping until i is no longer smaller than n (i < n
).
After each loop, the value of i is incremented by 1 (i++
)
Inside the for loop, we are multiplying the current value of result by x, and assigning the result back to the value of result (result *= x
)
1 Like
ayanda
(ayanda)
September 1, 2020, 10:06am
3
I totally get it! Especially right after the
" We continue looping until i is no longer smaller than n ( i < n
)"
Its quite the rush understanding something that wasnt before. Thank you.
It certainly is — I still get this very often.
Glad I could be of help