# Generate colors between #CCCCCC and #3B5998 for a color meter with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

We have to write a function that generates a random color between two given colors. Let’s tackle this problem in parts −

• First → We write a function that generates a random number between two given numbers.

• Second → Instead of using the hex scale for random color generation, we will map the hex to 0 to 15 decimal scale and use that instead.

• Lastly → We loop over any of the given color strings and generate a random color.

## Example

const randomBetween = (a, b) => {
const max = Math.max(a, b);
const min = Math.min(a, b);
return Math.floor(Math.random() * (max - min) + min);
};
const randomColor = (firstColor, secondColor) => {
first = firstColor.toUpperCase().substring(1, secondColor.length);
second = secondColor.toUpperCase().substring(1, firstColor.length);
const scale = '0123456789ABCDEF';
let color = '#';
for(let i = 0; i < first.length && i < second.length; i++ ){
const random = randomBetween(scale.indexOf(first[i]),
scale.indexOf(second[i]));
color += scale[random];
};
return color;
};
console.log(randomColor('#34324a', '#42342c'));
console.log(randomColor('#f43250', '#12342c'));
console.log(randomColor('#34324a', '#47942c'));
console.log(randomColor('#ffffff', '#000000'));

Following is the possible output in the console −

Note − This is just one of the many possible outputs as the output is random everytime.

## Output

#33332A
#C23328
#36822B
#35102A
Updated on 21-Aug-2020 15:01:44