This episode talks about the most efficient way to generate a random hex colour that will always be exactly 6 digits. Full Interview Question Playlist: • JS Interview - Timeout... Starter Code GIST: gist.github.com/prof3ssorSt3v...
Dude you videos are so cool. Like, quick and to the point. Even in the basic ones I learn something new and I've been doing all of this for a while. Well done, please never stop making JS videos haha.
Thank you sooo much! I found some solution on stack overflow before this but all that base number 10 16 talk was confusing me. After watching your video I am no longer confused. Thanks for explaining the solution to the problem and the base numbers thing so nicely!
function generateRandomColorHex() { return `#${Math.floor(Math.random() * 16777215).toString(16)}`; } for those who wonder what's 16777215 - it's evaluated value of (256 ^ 3) - 1, meaning 0-255 for each channel r, g, b
For Didactic purposes: function generate() { const red = Math.floor(Math.random() * 256).toString(16); const green = Math.floor(Math.random() * 256).toString(16); const blue = Math.floor(Math.random() * 256).toString(16); return `#${red + green + blue}`; } but it makes no sense to do this way, just for the sole purpose of understanding what's going on step by step. otherwise this is repetitive code which breaks DRY (Don't Repeat Yourself) Principles
The problem with that solution is that you get a number that can be any number of digits between 1 and 6. For CSS you must have 3, 6 or 8 digits, most commonly 6.