Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge, Part 2

James Estrada
James Estrada
Full Stack JavaScript Techdegree Student 25,862 Points

My Solution Adapted to Latest Content and Practices

let html = '';
let rgbColor;

const randomRGB = () => Math.floor(Math.random() * 256 );

const randomColor = () => `rgb(${randomRGB()}, ${randomRGB()}, ${randomRGB()})`;

const print = message => document.querySelector('#color').innerHTML = message;

for (let i = 0; i < 100; i++) {
  rgbColor = randomColor();
  html += `<div style="background-color:${rgbColor}"></div>`;


1 Answer

Interesting to see other people's solutions. I ended up going down a similar route. Need to try to get used to arrow functions, as it seems to save some space.

function randomRGB() {
  return `${Math.floor(Math.random() * 256 )}`;

function rgbColor() {
  return `rgb(${randomRGB()}, ${randomRGB()}, ${randomRGB()})`

for (var i = 0; i < 10; i += 1) {
  document.write(`<div style="background-color: ${rgbColor()}"></div>`);

Being a bit bored with the lockdown, I thought I'd try to see if I could shorten your code further. Came up with the below, although now watching the solution video I see I probably shouldn't have the document.write inside the loop. Anyways, was still fun.

const randomRGB = () => Math.floor(Math.random() * 256 );

const randomColor = () => `rgb(${randomRGB()}, ${randomRGB()}, ${randomRGB()})`;

for (let i = 0; i < 10; i++) {
   document.write(`<div style="background-color:${randomColor()}"></div>`);