0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Generate Random Color

Use const randomColor = '#' + Math.floor(Math.random() * 16777216).toString(16).padStart(6, '0'); to generate a random hex color string in JavaScript.
📋

Examples

InputRun program once
Output#3e92cc
InputRun program once
Output#a1f0b3
InputRun program once
Output#000000
🧠

How to Think About It

To create a random color, think of colors as numbers in base 16 (hex). We generate a random number between 0 and 16777215 (which is the decimal for 'ffffff' in hex), then convert it to a hex string. We add a '#' in front to make it a color code.
📐

Algorithm

1
Generate a random number between 0 and 16777215 inclusive.
2
Convert this number to a hexadecimal string.
3
If the hex string is shorter than 6 characters, add leading zeros.
4
Add a '#' character at the start to form a color code.
5
Return the resulting string.
💻

Code

javascript
function generateRandomColor() {
  const randomNumber = Math.floor(Math.random() * 16777216);
  const hexString = randomNumber.toString(16).padStart(6, '0');
  return '#' + hexString;
}

console.log(generateRandomColor());
Output
#a1f0b3
🔍

Dry Run

Let's trace generating a random color with a random number 10526835.

1

Generate random number

randomNumber = 10526835

2

Convert to hex string

hexString = 'a0f0b3'

3

Pad hex string if needed

hexString length is 6, no padding needed

4

Add '#' prefix

color = '#a0f0b3'

5

Return color

Output: '#a0f0b3'

StepValue
Random number10526835
Hex stringa0f0b3
Final color#a0f0b3
💡

Why This Works

Step 1: Random number generation

We use Math.random() multiplied by 16777216 to get a number in the full range of hex colors.

Step 2: Convert to hex

The number is converted to base 16 string with toString(16) to represent a color code.

Step 3: Padding

If the hex string is less than 6 characters, padStart(6, '0') adds zeros to keep the color code valid.

Step 4: Add '#' prefix

Adding '#' makes the string a valid CSS color code.

🔄

Alternative Approaches

Generate RGB components separately
javascript
function randomRGBColor() {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  return `rgb(${r}, ${g}, ${b})`;
}
console.log(randomRGBColor());
This method returns colors in rgb format, which some prefer for clarity but is longer than hex.
Use CSS HSL format
javascript
function randomHSLColor() {
  const h = Math.floor(Math.random() * 360);
  const s = Math.floor(Math.random() * 101) + '%';
  const l = Math.floor(Math.random() * 101) + '%';
  return `hsl(${h}, ${s}, ${l})`;
}
console.log(randomHSLColor());
HSL colors are easier to adjust for brightness and saturation but less common for random colors.

Complexity: O(1) time, O(1) space

Time Complexity

The program runs in constant time because it performs a fixed number of operations regardless of input.

Space Complexity

It uses constant space for variables and returns a fixed-length string.

Which Approach is Fastest?

All approaches run in constant time; generating a single random number and converting it is fastest and simplest.

ApproachTimeSpaceBest For
Hex random numberO(1)O(1)Simple hex color codes
Separate RGB componentsO(1)O(1)Readable rgb format
HSL formatO(1)O(1)Adjustable color properties
💡
Use padStart(6, '0') to ensure your hex color always has 6 digits.
⚠️
Forgetting to pad the hex string can cause invalid or short color codes.