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);
7 Answers 7
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));
7 Comments
while, I have made the updates.&& years++ which makes unnecessary calcs too. As programmers we should make code cleaner, because that can show up in bigger projects where you need to create something which does perform better in speed etc. But yeah, that explains the root of the issue, so good answer gurvinder372It gets executed only once because the value of years used for checking truthiness is 0, i.e. before incrementing.
Comments
You should use years++ inside the loop:
function calculateYears(investment, interestRate, tax, desiredProfit) {
var years = 0;
while(investment < desiredProfit){
investment += (investment * interestRate) * (1 - tax);
years++;
}
return years;
}
alert(calculateYears(1000, 0.05, 0.18, 1100));
Comments
while(investment < desiredProfit && ++years)
this condition will not execute because as years is 0 and it increment after the 1 loop so it is like
desiredProfit && 0 -> false/0
and after
investment < 0 //is always false
Comments
You did forget that your while loop is not incrementing the value of years
while(investment < desiredProfit && ++years){
investment += (investment * interestRate) * (1 - tax); years++;
}
Comments
Why not do something like this
let i = -6;
let end = 9;
while ((i++ || true) && i < end) {
...do something...
}
Comments
Because && years++ translates to && 0 which will translates to false value.
If you want to use years++, initialize years to 1.