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, end=Math.sqrt(n); i <= end; 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 : 05/04/2023