Question about Javascript function that exponentiates two numbers

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

no, x is the same value

to check add console.log(x) whenever you want to check

result *= x is the same as result = result * x which uses the value of x but doesn’t change it

:grinning: That cleared it up for me, much appreciated.