Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

for loop stops after first iteration JS

so am doing this exercise where it asks me to return a list of strings for each counted number.

I am aware that the function will end as soon as it return a value. I tried couple of other variations such as continue and break, but i cant seem to figure it out.
Thank you in advance

var countSheep = function (num) {
    for (let i = 1; i <= num; i++) {
        return `${i}sheep...`;
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As mentioned in the comments by Barmar, you can add the values to an array and return the list after the for loop completes. That would look like:

var countSheep = function (num) {
  var list = [];
  for (let i = 1; i <= num; i++) {
      list.push(`${i}sheep...`);
  }
  
  return list
}

console.log(countSheep(3))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading