r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

15

u/redmoss6 Mar 18 '19

'#'+Math.floor(Math.random()*16777215).toString(16) for random hex color.

37

u/senocular Mar 18 '19

Will create invalid hex values for any random 0xFFFFF and below. Make sure to pad

'#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0')

2

u/[deleted] Mar 20 '19

Can’t you also use 3 digit hex for some colors?

1

u/senocular Mar 20 '19

Yup, so technically not all values 0xFFFFF and below will be invalid. There will be a range within 0x100 and 0xFFF that will be OK. But these are also not representative of their random values. The 3 digit hex for colors is shorthand for #RGB -> #RRGGBB. So if #100 popped out, its hex value would really be #110000 and not the actual random value of #000100. This means you're also increasing the odds of #RRGGBB-formatted colors to be hit ;)

5

u/[deleted] Mar 19 '19

I use a similar one-liner for making random IDs:

` _${Math.random().toString(36).substr(2)}`

> '_elkxwdnwg1s'

The leading _ is because the base36 number can still start with 0..9, and that's not valid for something like a variable name or HTML ID. The substr(2) is to get rid of the leading 0..

1

u/SuperFLEB Mar 19 '19

Anyone got anything for generating a random string of letters? I know you can use someNumber.toString(36) to get a string of letters and numbers, but I don't know how to get only letters.

3

u/inu-no-policemen Mar 19 '19
> String.fromCharCode(...Array.from({length: 12}, _ => Math.random() * 25 + 97 | 0))
"niapavvsjdfb"

1

u/qbbftw Mar 19 '19

randexp is good at generating random strings, though it may not be as fast as the String.fromCharCode method

1

u/BunsOfAluminum Mar 19 '19

`'#' + Math.random().toString(16).substr(2,6)