JavaScript Program to Generate Random Color
const randomColor = '#' + Math.floor(Math.random() * 16777216).toString(16).padStart(6, '0'); to generate a random hex color string in JavaScript.Examples
How to Think About It
Algorithm
Code
function generateRandomColor() { const randomNumber = Math.floor(Math.random() * 16777216); const hexString = randomNumber.toString(16).padStart(6, '0'); return '#' + hexString; } console.log(generateRandomColor());
Dry Run
Let's trace generating a random color with a random number 10526835.
Generate random number
randomNumber = 10526835
Convert to hex string
hexString = 'a0f0b3'
Pad hex string if needed
hexString length is 6, no padding needed
Add '#' prefix
color = '#a0f0b3'
Return color
Output: '#a0f0b3'
| Step | Value |
|---|---|
| Random number | 10526835 |
| Hex string | a0f0b3 |
| 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
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());
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());
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Hex random number | O(1) | O(1) | Simple hex color codes |
| Separate RGB components | O(1) | O(1) | Readable rgb format |
| HSL format | O(1) | O(1) | Adjustable color properties |
padStart(6, '0') to ensure your hex color always has 6 digits.