- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Changing color randomly in JavaScript
We are required to write a JavaScript function, let’s say randomColor that returns a randomly generated hex color every time it is called.
Example
Following is the code −
const randomColor = () => { let color = '#'; for (let i = 0; i < 6; i++){ const random = Math.random(); const bit = (random * 16) | 0; color += (bit).toString(16); }; return color; }; console.log(randomColor()); console.log(randomColor()); console.log(randomColor()); console.log(randomColor()); console.log(randomColor()); console.log(randomColor()); console.log(randomColor());
Output
This will produce the following output in console −
#762b46 #cfa0bf #a20ee1 #c2f7e0 #5d5822 #380f30 #805408
Advertisements