It’s when the RGB values are less than 16. The toString(16) will give you a single digit, but hex colors need two digits for each R, G, B. You need to pad with a leading zero if the value is less than 16. Like r.toString(16).padStart(2, '0').
Spot the Bug answer: The formatHexColor function does not pad single-digit hexadecimal color components with a leading zero, leading to invalid 3-digit or 5-digit hex codes.
Why:
Hexadecimal color codes require each component (red, green, blue) to be represented by exactly two characters. When a component’s value is less than 16 (e.g., 5), its toString(16) representation is a single digit (‘5’). The function concatenates these single digits directly, resulting in incorrect hex strings like ‘#5a0f’ instead of ‘#050a0f’.
Nice catch, @BobaMilk. The part I liked most was how you pinned it to values under 16, instead of just saying the hex looked wrong. That single-digit case is exactly the kind of thing that slips through because most test colors look fine.
And yeah, padStart(2, ‘0’) is the clean fix here. No need to overcomplicate it with a bunch of conditionals when that one call does the job.