PapaYoda
PapaYoda

Reputation: 19

Return a for loop inside a function

i have a function with a for loop inside it, this function should later display the values, something like a Button click handler. How can i return the values (in this case 10 times) in this for loop instead a console.log(), if i try with return statement, after 1 iteration logically break return the loop.

const handleCalculate = () => {
  let price = 6.60;
  let growthRate = 12.35;
  let yearlyGrowth = (growthRate * price) / 100;
  let currentPrice = price + yearlyGrowth;
  // should output 10 times
  for (let i = 0; i <= 10; i++) {
    currentPrice += yearlyGrowth;
    currentPrice = Math.round(currentPrice * 100) / 100;
    // how can i return each values instead of console.log() ?
    console.log(currentPrice);
  }
}
handleCalculate();

EDIT ! first Thank at all for quick answer! i modifying my Code and work fine, but i wanna know it is a good practice? Can you improved it?

// Calculate growing fish price
const growthCalculator = () => {
  const price = 6.60;
  const growthRate = 12.35;
  const yearlyGrowth = (growthRate * price) / 100;
  const result = [];

  let currentPrice = price + yearlyGrowth;

  // Calculate each growing fish price and round it to 2 decimal
  for (let i = 0; i <= 10; i++) {
    currentPrice += yearlyGrowth;
    currentPrice = Math.round(currentPrice * 100) / 100;

    // push result in new array
    result.push(currentPrice);
  }
  return result;
}
const result = growthCalculator();

//Loop thru result array and display fish price
const handleCalculator = () => {
  let summe = '';
  result.forEach(element => {
    summe += element + "<br>";
    document.getElementById("demo").innerHTML = summe;
  });
}
// display result by button click
document.getElementById("btn").addEventListener('click', handleCalculator);

Upvotes: 1

Views: 1138

Answers (4)

Dessus
Dessus

Reputation: 2177

The way to do it in the specific way you have asked the question is to use the yield return. This is documented here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield

Essentially instead of using return (which breaks the loop) you use yield which returns a value of an iterable (but only when iterating that far). This is a great way to program as you could say have 10,000 items but have a consumer only ready the top 10 etc. This would prevent the need to process all 10,000 for someone only wanting a few items. This approach would also mean less than a 1 line change for you.

It also means that you don't need to create an array as in the other answers.

const handleCalculate = () => {
  let price = 6.6;
  let growthRate = 12.35;
  let yearlyGrowth = (growthRate * price) / 100;
  let currentPrice = price + yearlyGrowth;

  for (let i = 0; i <= 10; i++) {
    currentPrice += yearlyGrowth;
    currentPrice = Math.round(currentPrice * 100) / 100;

    /* Add current price of this iteration to end of array */
    yield currentPrice;
  }
};

console.log(handleCalculate().next().value); //this only loops once in that for loop. Note: handleCalculate() returns an iterable (meaning its only executed once .next() or similar is called on it. This makes it lazy evaluated.
console.log(handleCalculate().next().value); //this is the 2nd iteration result
console.log(Array.from(handleCalculate()); //this forces execution of your entire for loop (like the other answers) and outputs an array.

Upvotes: 0

Dacre Denny
Dacre Denny

Reputation: 30360

One solution would be to create an array inside of handleCalculate() that stores the currentPrice value of each iteration, and then return that array after the loop has completed:

const handleCalculate = () => {

  /*Declare empty array like this */
  let resultsArray = [];

  let price = 6.6;
  let growthRate = 12.35;
  let yearlyGrowth = (growthRate * price) / 100;
  let currentPrice = price + yearlyGrowth;

  for (let i = 0; i <= 10; i++) {
    currentPrice += yearlyGrowth;
    currentPrice = Math.round(currentPrice * 100) / 100;

    /* Add current price of this iteration to end of array */
    resultsArray.push(currentPrice);
  }

  /* Return the array */
  return resultsArray;
};

console.log(handleCalculate());

Upvotes: 1

charliemei
charliemei

Reputation: 11

Maybe it is ok?


``const handleCalculate = () => { 
  let price = 6.60;
  let growthRate = 12.35;
  let yearlyGrowth = (growthRate * price) / 100;
  let currentPrice = price + yearlyGrowth;
  return ()=>{
    currentPrice += yearlyGrowth; 
    currentPrice = Math.round(currentPrice * 100) / 100;
    //how can i return each values instead of console.log()?
    //console.log(currentPrice);
  }
}
btn.addEventListener('click',handleCalculate())

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97152

Aggregate your results in an array, and return the array:

const handleCalculate = () => {
  const price = 6.60;
  const growthRate = 12.35;
  const yearlyGrowth = (growthRate * price) / 100;
  const result = [];
  
  let currentPrice = price + yearlyGrowth;
  
  for (let i = 0; i <= 10; i++) {
    currentPrice += yearlyGrowth;
    currentPrice = Math.round(currentPrice * 100) / 100;
    
    result.push(currentPrice);
  }
  
  return result;
}

const result = handleCalculate();

console.log(result);

Upvotes: 1

Related Questions