w3resource

JavaScript: Generate a random hexadecimal color code

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

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 
const random_hex_color_code = () => {
  let n = (Math.random() * 0xfffff * 1000000).toString(16);
  return '#' + n.slice(0, 6);
};

console.log(random_hex_color_code())

Sample 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.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to extract out the values at the specified indexes from an specified array.
Next: Write a JavaScript program to removes non-printable ASCII characters from a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



JavaScript: Tips of the Day

Returns an array of n-tuples of consecutive elements

Example:

const tips_arr = (n, arr) =>  n > arr.length ? [] : arr.slice(n - 1).map((v, i) =>[...arr.slice(i, i + n - 1), v]);
console.log(tips_arr(2, [1, 2, 3, 4, 5])); 
console.log(tips_arr(3, [1, 2, 3, 4, 5]));
console.log(tips_arr(5, [1, 2, 3, 4]));

Output:

[[1, 2], [2, 3], [3, 4], [4, 5]]
[[1, 2, 3], [2, 3, 4], [3, 4, 5]]
[]