Do me a favor, take a few seconds to have a look at my last project.

Thank you, Lulu

How to check if a number is prime in JavaScript

The following function returns true if the parameter n is a prime number:

// Return true if n is prime
function isPrime(n) 
    // Check if n is less than 2 => not prime
    if (n<2) return false;

    // Loop from 2 to square root of n
    for (let i = 2; i <= Math.sqrt(n); i++) 
        // If i is a divisor of n, n is not prime
        if (n % i == 0) return false;

    return true;

This function check every divison between 2 and square root of n. If n is not prime, there is necessarily a divisor in this interval.

See also

Last update : 04/13/2019