Generating non-repeating random colour from the array in JavaScript


Can any one please help me. Basically, I’m trying to create a non-repeating random colour from the array and use that random colour to add to the body tag as background colour. The problem is the random colour is “undefined” at one stage.

Here is my code:

//Create array of colours
let colours = ["lightgreen", "orange", "pink", "lightblue", "brown"];

let button = document.querySelector(".button");
let hexcode = document.querySelector(".hexcode");

//Inital default background colour
document.addEventListener("DOMContentLoaded", () =>{ = colours[0]; 
    hexcode.textContent = colours[0];

//Generate the inital random colour
let randomColour = 0;

//Click event on the button
button.addEventListener("click", () =>{
    //Create empty array
    let array = [];

    //Create the for loop to prevent duplicates
    for(let i = 0; i < colours.length; i++){
      if(i != randomColour){

    //Random colour
    randomColour = array[Math.floor((Math.random() * colours.length))];

    //Add the colour to the body as background colour = colours[randomColour];     
    hexcode.textContent = colours[randomColour];



So you can probably keep records with a set. A set only keeps single instances of a value. So when you generate a number, check if it’s in the set, if it’s not you haven’t used it yet. Use it and put it in the set.