This site uses third-party cookies, learn more or accept

Javascript Prime Number generator

Create a simple prime number generator with Javascript
Written by Maxwell Pelic,

Ever wanted to create a prime number generator? You can make a really basic one with Javascript, or use this approach to create one in a different programming language. Here’s the basic code:

//list of all prime numbers

var primes = [2];

//current number

var current = 1;

//function to generate primes

var getPrimes = function(){

    //add 2 since even numbers are never prime

    current += 2;

    for(var i = 0; i < primes.length; i++){

        //cycle through generated prime numbers and check if the current number is divisible by any of them

        if( current % primes[i]  === 0){

            //number is divisible by a prime number




    //add the prime number to the array



//set interval to keep generating prime numbers

window.setInterval(getPrimes, 1);

To view the generated prime numbers, open the Developer Console in your web browser (press ctrl+shift+i for chrome), type in primes and press enter.

That’s it! Go crack some codes

Previous Article: 3 Ways to Include Files on Your Website

Next Article: Create a PHP Blog - no Database Needed!