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

James Estrada
seal-mask
.a{fill-rule:evenodd;}techdegree
James Estrada
Full Stack JavaScript Techdegree Student 25,866 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>`;
}

print(html);

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>`);
}