0

I somehow can't get my for loop inside of a function to print elements in an array. could someone point out why javascript is not allowing the iteration to occur and only printing the first element?

const data1 = [17, 21, 23];

function printForecast(array) {
  for (let i = 0; i < array.length; i++) {
    let dayVsDays = i <= 1 ? 'day' : 'days'
    return `The temp is ${array[i]}ºC in ${[i+1]} ${dayVsDays}`;
  }
}

console.log(printForecast(data1))
Andy
  • 61,948
  • 13
  • 68
  • 95
  • That return will shortcut the loop so it will quit the function after the first iteration. – Andy May 22 '22 at 11:42

1 Answers1

1

Don't use return inside a loop unless you want to return the result of an specific iteration; this is why you only get the first iteration.

eriktvj
  • 21
  • 2