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));
Answer from gurvinder372 on Stack OverflowI 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));
It gets executed only once because the value of years used for checking truthiness is 0, i.e. before incrementing.
MDN Documentation
Videos
((x+=2) < n)
x+=2 is a shorthand for x=x+2;
if x=0 initially the condition that would be checked would be 2 < n
(x < n) {...x += 2}
if x=0 initially the condition that would be checked would be 0 < n
Main difference is you are incrementing first and then checking the condition in first one while in second one you check and then increment x.
So your question is what's the difference between...
while ((x+=2) < n) {}
AND
while(x < n) { x+=2 }
The main difference is that in the first example, the x gets the 2 added on and is then compared to the value of n, whereas in the second example, x is compared to n before the 2 has been added and will therefore most likely run 1 more loop than you would expect