Search code examples
javascriptloopswhile-looppow

trying to understand this math.pow loop ,dont understand why the exponent has to be reduced by 1


help me understand this:

function myPow(base, exponent) {
    var count = 0
    var power = base
    while (exponent-1 > count) {
        power *= base

        count++

    }
    return sum;
}

why do we exponent-1? for example if the numbers are 2,3 then we would basically get 2*2 and not 2*2*2?


Solution

  • Because by doing this:

    var power = base;
    

    You're already taking care of the first exponent.

    If you do this instead:

    var power = 1;
    

    Then your while loop can be:

    while (exponent > count){
        ...
    }
    

    Note Your function is returning sum, but that doesn't exist.