Get random item from JavaScript array

Published on August 27th, 2019

javascript icon

This one is also one of those that pop up every few weeks and I always have to search through visited Stack Overflow answers.

Okay, lets get to the point. You have an array similar to this…

const hexCodes = ['#0e8fd5', '#663399', '#212121']

…and you want to get random item from it.

const randomHexCode = hexCodes[Math.floor(Math.random() * hexCodes.length)]