donut imageCodenut.dev
Blog
About
Portfolio
published: September 20, 2022
Article author picture
Kain NhantumboWeb Developer & Designer
Share:
Read: 1 minutesWords: 284Characters: 1884

How to Generate Random Colors in Javascript

Javascript

Learn how to generate colors in javascript programmatically

Table of Contents

  • Generating the colors

In this post, I will write a quick guide to build a simple hexadecimal color generator with javascript, so you can use it in your projects.

Without much, let's begin.

Generating the colors

First, we have to create an array of hexadecimal caracteres like this:

js
1const charactersArray = [0,1,2,3,4,5,6,7,8,9,"A","B","C","D","E","F"]

Putting those characters in an array will simplify the process, thats why I have picked an array to allow us to select any item by providing its index.

Then, let's create a function to select items from the array we created:

js
1// function that takes a index and returns an integer.
2function getHexCharacter(index) {
3  return charactersArray[index];
4}

The function above will take the index and return the hexadecimal-character stored in that place. Next, we need to represent colors using the returned value.

js
1function generateColor() {
2  const hexColorCode = '#'; // initial hex color code
3
4  // iterate over the 6 possible additional characters for the color code
5  for (const i = 0; i < 6; i++) {
6    const randomIndex = Math.floor(Math.random() * charactersArray.length);
7    hexColorCode += getHexCharacter(randomIndex);
8  }
9  return hexColorCode;
10}

The above function, loops 6 times because hexadecimal colors are represented by 6 hexadecimal digits. Within the loop, the function calls getHexCharacter() to generate a hexadecimal digit for each index of the color code.

The function getHexCharacter() takes the randomIndex generated from the array of characters we have created before as parameter to ensure that we not have te same generated calor code values. Once all digits of the color code have been generated, the function generateColor() returns the complete hexadecimal color code represented as a string.

That's it. I hope you could learn something new today. Thank you for reading!

Get in touch

Donuts combo decoration image

Crafted with ❤ using Next.js and Typescript.

© 2025 Kain NhantumboVersion 6.3.0-09-2024