w3resource

JavaScript: Generate a random hexadecimal color code

JavaScript fundamental (ES6 Syntax): Exercise-11 with Solution

Generate Random Hexadecimal Color Code

Write a JavaScript program to generate a random hexadecimal color code.

  • Use Math.random() to generate a random 24-bit (6 * 4bits) hexadecimal number.
  • Use bit shifting and then convert it to an hexadecimal string using Number.prototype.toString(16).

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
// Define a function called `random_hex_color_code` that generates a random hexadecimal color code.
const random_hex_color_code = () => {
  // Generate a random number and convert it to hexadecimal string representation.
  let n = (Math.random() * 0xfffff * 1000000).toString(16);
  // Return the hexadecimal color code with '#' appended.
  return '#' + n.slice(0, 6);
};

// Test the function
console.log(random_hex_color_code()); // Output: Random hexadecimal color code

Output:

#2375d4

Flowchart:

flowchart: Generate a random hexadecimal color code

Live Demo:

See the Pen javascript-basic-exercise-1-11 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that generates a random hexadecimal color code using Math.random and bitwise operations.
  • Write a JavaScript function that produces a random hex color string with or without the '#' prefix.
  • Write a JavaScript program that continuously generates random hex colors until a shade of blue is produced.

Go to:


PREV : Extract Values by Indexes from Array.
NEXT : Remove Non-Printable ASCII from String.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.