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

My Refactor Challenge Solution

Hi all šŸ‘‹šŸ»,

const main = document.querySelector('main');

for (let i = 1; i <= 10; i++) {
  const randomRGB = `rgb(${Array.from({ length: 3 }, () => Math.floor(Math.random() * 256)).join(', ')})`;
  main.innerHTML += `<div style="background-color: ${randomRGB}">${i}</div>`;
}

Think this is quite concise! I know if we're following the track we haven't got to arrays yet, but I'm just in the process of restarting my journey to learn JavaScript, so I've applied some previously gained knowledge here!

Also been trying to make improvements the challenges given in the track so far, if anyone is interested, I've added repos to my GitHub, which are accessible through my profile page.

Mark Sebeck
Mark Sebeck
Treehouse Moderator 37,515 Points

Nice job Berian Lowe . I like the idea of enhancing the projects and putting on Github. You are building a nice little porfolio there. Keep up the good work!

1 Answer

Steven Parker
Steven Parker
229,783 Points

That's pretty clever! ā€ƒ :+1:

But if you're going for concise, instead of the object with explicit length ({ length: 3 }) you could just have an array literal ([1,2,3]). And then, since you have an array to begin with, you can compact it even more by just calling map on it directly:

  const randomRGB = `rgb(${[1,2,3].map(() => Math.floor(Math.random() * 256)).join(', ')})`;

ā€ƒ :wink: