Javascript puzzle (I'm stuck)

Hey Everyone,

I am new to Javascript and have been banging my head against the wall for a few hours on this one. Below are the parameters of the problem and my current solution.

Parameters:

You put 1000 dollars into a new cryptocurrency. Good luck! Over ten years, the value of the investment increases by 5% each year. In the seventh year, the investment loses 75% instead of increasing. Eeek! Use a for loop to log how many years it has been and how much the investment is worth for each year.

Solution (so far):

let investment = 1000;

for (var year = 1; year <= 10; year++){
  investment = investment + investment * 0.05;
 console.log("In year " + year + " your investment was worth " + "$" + investment);
}

I have figured out how to increase the value of the investment by 5% each year, but I can’t figure out how to make it drop by 75% in year 7.

Please help point me in the right direction. Thank you for your help :).

-Buddha Blake

@buddhablake You will need to add some conditional logic to do something different when year is equal to 7.

Thank you for the pointer, I think I found a solution.

let investment = 1000;


for (var year = 1; year <= 10; year++){
  if(year === 7){
    investment = investment * .25;
  }
  else{
  investment = investment + investment * 0.05;
  };
  console.log("In year " + year + " your investment was worth " + "$" + investment);
}

How does that look? It gives me the result I’m looking for, but does it follow best practices?

If it achieves your goal, that is what is important. You could do something similar like the following to shorten your code a bit. It uses the ternary operator.

let investment = 1000;

for (var year = 1; year <= 10; year++){
  var percentChange = year === 7 ? 0.25 : 1.05;
  investment *= percentChange;
  console.log("In year " + year + " your investment was worth " + "$" + investment);
}

Nice! I had no idea the ternary operator even existed. Thanks, @RandellDawson.

-Buddha Blake