Search code examples
javascriptwhile-loopincrement

While loop and increment in JavaScript


In the following function I need to increment the years variable in order to find the amount of years that need to pass before I reach a desired profit. I noticed that this function does not work if I use years++ instead of ++years. I understand the difference between the two methods of increment, however, I still do not understand while in this particular case years++ causes the loop to be executed only once.

 function calculateYears(investment, interestRate, tax, desiredProfit) {
        var years = 0;
        while(investment < desiredProfit && ++years){
          investment += (investment * interestRate) * (1 - tax);
        }
    
        return years;
    }
    var years = calculateYears(1000, 0.05, 0.18, 1100);
    console.log(years);


Solution

  • I still do not understand while in this particular case years++ causes the loop to be executed only once.

    because && years++ translates to && 0 which will translates to falsey value.

    If you want to use years++, initialize years to 1

    function calculateYears(investment, interestRate, tax, desiredProfit) {
        var years = 1;
        while(investment < desiredProfit && years++){
          investment += (investment * interestRate) * (1 - tax);
        }
    
        return years - 1;
    }
    console.log(calculateYears(1000, 0.05, 0.18, 1100));