My Books

Text Processing with JavaScript

Solve complex text validation, extraction, and modification problems efficiently in JavaScript.

Modern Async JavaScript

Delve into async features of JavaScript from ES2020 through ESNext. Start building custom asynchronous iterators and generators, and more for fast, lean code.

JavaScript Brain Teasers

Ready to test your JavaScript skills? Challenge yourself with these brain-teasing puzzles, supercharge your learning journey, and emerge as a JavaScript pro.

Random Lottery Number Generator

In this post I will show you how easily you can generate a random lottery number using javascript.

Generating a random lottery number can be easily done in Javascript. The following code generates nine two-digit random numbers and displays them in a paragraph. To change the number of digits simply change the value of “numbers” variable at the head of the javascript code. Whenever the page is loaded a new number will be generated.

Here is the html:

<!doctype html>

<html lang="en">

<head>

    <meta charset="utf-8">

    <title>Random lottery number </title>

</head>

<body>

    <p>Winning Numbers: <span id="result"></span></p>

    <script src="random.js"></script>

</body>

</html>

The javascript:

function displayNumbers() {

    'use strict';

    var numbers = 9; // replace 9 with your desire number

    var r= '';

    for (var i = 0; i < numbers; i++) { 

                  r += parseInt((Math.random() * 100), 10) + ' ';

    }

    var result= document.getElementById('result');

    if (result.textContent !== undefined) {

               result.textContent = r;

    } else {

               result.innerText = r;

    }

}

window.onload = displayNumbers;

Related: Creating a Random Integer in Javascript

2 comments

  1. Pingback: Random Integer in Javascript

Have your say