Search code examples
javascriptarraysfunctionvariables

How to save the result of a variable in a loop


function priceDiscountSeries(originalPrice, discountSeries) {
    let netPrice = originalPrice;
    for (let i = 0; i < discountSeries.length; i++) {
        netPrice = originalPrice * (1 - discountSeries[i]);
    }
    return netPrice;
}

console.log(priceDiscountSeries(94_500, [0.40, 0.10, 0.05]));

What I'm trying to do is to have the result saved on a variable, then use that variable to return another result, which is again saved on the variable itself.


Solution

  • Just replace:

    netPrice = originalPrice * (1 - discountSeries[i]);
    

    with

    netPrice *= (1 - discountSeries[i]);
    

    Should give you the result you're looking for.

    However, you could use reduce to perform the same operation, having a simple arrow function for the price discount:

    const priceDiscount = (price, discount) => price * (1 - discount);
    
    const discountSeries = [0.40, 0.10, 0.05];
    
    console.log(discountSeries.reduce(priceDiscount, 94_500));