Q:

Trying to figure out code snippet in the book Eloquent JavaScript

Chapter 3 Functions has the following code snippet:
const power = function(base, exponent) {
let result = 1;
for(let count = 0; count < exponent; count++) {
result *= base;
}
return result;
}; 
console.log(power(2, 10));
// 1024

can someone explain what is going on in the code line by line, i'm confused by let result = 1 the most. Thanks!

A:

In the first line, you're declaring a variable result. However, it's being declared with let, not var. Let is similar to var, except it can't be accessed outside the block it is defined in (including functions, loops and conditional statements). And since it's in a function here, that first line is equivalent to:
var result = 1;

In the second line:
for (let count = 0; count < exponent; count++) {}

You're looping over exponent - so the code within the {} of the loop will be executed exponent times.

In the third line:
result *= base;

You're multiplying result and base, and assigning the value to result. This line is equivalent to:
result = result * base;

Final line:
return result;

This line stops the function and returns result. The return means that whenever a function is called, it essentially is replaced with the return value (like in this line):
console.log(power(2, 10));

This calls power() with arguments 2 and 10, and logs the returned value to the console.

