eddie
eddie

Reputation: 29

Implement power function in javascript

I would like to understand how this program (copied from the eloquent javascript) works.

The actual program: a function with two parameter names (base, exponent), if you give those two parameters, the program should make the square of the base.

I tried to solve it on my own, but I failed.

Let me copy the code here:

const power = function(base, exponent) {
  let result = 1;
  for (let count = 0; count < exponent; count++) {
    result *= base;
  }
  return result;
};
console.log(power(2, 10));

I understand well that I have to multiply the base with itself exponent times but I can not see how this program solves that. I had various other ideas, but... :)

I do not understand the result and count section, however it has been declared, but I can not see how it works.

Could somebody explain it to me? How does count affect the result?

Upvotes: 2

Views: 2761

Answers (1)

NiVeR
NiVeR

Reputation: 9796

This is the implementation of the power, x^y (on calculator), function. You basically start by defining the product to be 1, because 1 is the invariant element for multiplication. And you go on and multiply the product by the base a exponent number of times times.

In your case, you have x = 2, y = 10:

result = 1 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 = 1024.

you have the first 1, and you multiply by 2 (base) 10 (exponent) times.

Upvotes: 3

Related Questions