Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops Working with 'for' Loops The Refactor Challenge – Duplicate Code

Sharing my solution (would love feedback!)

let html = '';
let randomNum = () => Math.floor(Math.random() * 256);

for ( let i = 1; i <= 10; i++ ) {
  html += `<div style="background-color: rgb(${randomNum()}, ${randomNum()}, ${randomNum()})">${i}</div>`;
}

document.querySelector('main').innerHTML = html;

Not the same as the instructors but it works. 🤷‍♀️

4 Answers

Hi Karla!

Yes, your code works just fine and in this context I think is just as efficient as Guil's.

Keep in mind that the primary reason to turn small blocks of code into functions is for reusability and to keep your code as DRY* as possible.

*(Don't Repeat Yourself: https://dzone.com/articles/is-your-code-dry-or-wet)

I think Guil's example approach would only be the better way to go if later in the code you needed many more randomRGB color values (it would ultimately be just slightly less typing, overall). Does that make sense?

Also, on the other hand, I think sometimes refactoring can go too far and make code difficult to understand. For example, in some complex platforms, such as WordPress, the code is so refactored and modular that locating where a function is declared can be difficult, if not impossible, and can make debugging and customing the code nightmarish!?!

I hope that helps.

Stay safe and happy coding!

Mohandas Towne
Mohandas Towne
3,718 Points

This is precisely what I did. Was very validating to see that you posted this example, thanks!

I love this solution. It's very easy to understand for a newbie, like myself. Thanks for sharing!

Dzmitry Aliakseichyk
Dzmitry Aliakseichyk
12,290 Points

Haha yeah I did it exactly the same way. As efficient as possible.