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, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge, Part 2

My code is working, but I don't know if it follows JS best practice. Can someone review it for me?

Below is my solution for this refactor challenge.

function randRGBVal() {
    return Math.floor(Math.random() * 256 );
}

function rgbColor() {
    return 'rgb(' + randRGBVal() + ',' + randRGBVal() + ',' + randRGBVal() + ')';
}

var html = '';

for (var i = 0; i < 10; i++) {
    html += '<div style="background-color:' + rgbColor() + '"></div>';
}

document.write(html);

As a JavaScript newbie, I wonder is anything in my code which would be flagged as the bad practice? I'm quite nervous about how the return value of rgbColor() relies on the return value of randRGBVal(). Thanks, everyone!

2 Answers

Bryan Peters
Bryan Peters
11,996 Points

I don't see anything wrong with what you are doing. The function names could be a little more descriptive - I usually like to have a verb in the name, as functions DO something like generateRandomColorVal() or getRandomColor(). Eventually when you learn about objects you may want to have a reusable color object with properties red, green, and blue, and a method that produces the rgb string in both hex and rgb format. But what you have is fine for where you are now.

Thank you so much for your advice, Bryan!

Rokas Mazeika
Rokas Mazeika
4,243 Points

it doesnt matter how you do the code the most important thing is that it works

Bryan Peters
Bryan Peters
11,996 Points

As someone who has had to maintain poorly written but functional code, I respectfully disagree with this statement.

Actually, that's 100% wrong. You might think "if it works, it's fine.", but it's different. If you had messy code (that still works), it is very hard to edit and/or add more code onto your script. It is very bad practice to write bad code.