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 in vanilla JavaScript

I have a rate number for 3 different products,
and i am trying to render a star svg base of number of rate.
for example product A has rate 3, I want to render star img, 3 times.
the maximum star they can have is 5.

i wrote a code like this

const ratingHandler = (productRate) => {
  for (let i = 0; i < productRate + 1; i++) {
    console.log(productRate);
    return `<img src="assets/star.svg" alt="rating-star" />`;
  }
};

product rate shows the rating number correctly in my console.log, but the render in the loop doesn’t render base of that number

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 :

Your function ends as soon as it first hits the return. You need to build up the complete string before returning:

const ratingHandler = (productRate) => {
  let stars = '';
  for (let i = 0; i < productRate + 1; i++) {
    stars += `<img src="assets/star.svg" alt="rating-star" />`;
  }
  return stars;
};
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