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

Random Number generator

Hi guys

I've made a random colour generator for something that I'm working on. Is there any way I can get the same result without repeating the first three lines.

function randomColour () {
    let r = Math.floor( Math.random() * (255 - 0) + 1 );
    let g = Math.floor( Math.random() * (255 - 0) + 1 );
    let b = Math.floor( Math.random() * (255 - 0) + 1 );
    let result = `rgb(${r},${g},${b})`;
    return result;
  }

Is there any way I can compact those three variables so they each get a different random number?

Thanks in advance

Paul

1 Answer

Steven Parker
Steven Parker
243,656 Points

You could always make another function and call it from this one. And you don't need to shift the range since 0 is a valid color component value:

var cv = () => Math.floor( Math.random() * 256 );
var randomColour = () => `rgb(${cv()},${cv()},${cv()})`;

Hey thanks Steven, it only works if I change the second line to a variable, not a function.

let result = `rgb(${rand()},${rand()},${rand()})`;

It works, now anyway. Thanks man

Paul

Just realised I was returning without the parethesis.....ignore me!