lottozahlen 23.05.20

JavaScript Lottery Number Generator

For the last fews weeks I have been doing different JavaScript projects to help increase my JavaScript skill set. I felt that creating a javascript lottery number generator was a good next project because I could build on top of what I have already learned. For this project, I would need to append my numbers onto elements, and I learned how to do that when I created the tip calculator and I was also already familiar with math.random().


  1. Generate 6 random numbers from 1 – 45
  2. Check for duplicates
  3. Store these number in an array
  4. Sort the array in ascending order
  5. Create an html element to hold each array value
  6. Append the array value to each element
  7. Delete circle elements before function starts

For the JavaScript lottery number generator I knew I wanted it to generate 6 random numbers from 1 – 45 and then store these 6 numbers in an array. I would have to use math.random for it. I would then have to create a function to check for duplicates and not add these duplicate numbers to the array. When winners are announced lottery numbers are shown in ascending order so my next step would be to arrange the array numbers from smallest to largest. I then would append these elements to my existing html.

To create the html I am using a bootstrap starter template. I created a button that upon clicking will fire up my javascript lottery number generator function. I then added a div with an id of lotto. This is where I will append my elements I create in the javascript lottery number generator function.

The CSS file contains styling for the layout, font, circles, hr elements, and the background image.


I first created an empty array. I then created a function that will keep iterating through until my array reaches 6 random values. If the value is a duplicate it will not add it into the array and continue until 6 different values are reached. In the next step, I sort the array into ascending order and stored those results into an array called sorted. I then used a foreach function. For each element of the array, I create a span element and add the circle class and m-3 classes to it. I then set the value of each circle element to the value of the array and I appended each element to my existing html.

After completing these steps, I realized if I clicked the function twice, my 6 existing lottery numbers remained, and 6 more were added in addition. If I did this 3 times, 6 more numbers would be added to the pile. To prevent this, I added an if statement at the top of my JavaScript lottery number generator function to check if an existing circle element exists and if so delete it. It is important to add this to the top of your function, and not at the bottom, otherwise it will delete all your circle elements upon creation.

A tutorial on how to make a JavaScript lottery number generator using HTML, CSS and JavaScript. ]]>