To check if a number is prime in JavaScript, we can write a function that loops through all the numbers from 2 to the square root of the given number and checks if any of them divide the given number evenly. If no numbers divide the given number evenly, then it is a prime number.
Here's the function:
527 chars12 lines
Here's an example usage of the function:
69 chars3 linesIn the example above, the isPrime function is called with argument 11 which is a prime number, so the output is true. Then, the function is called again with argument 16 which is not a prime number, so the output is false.
gistlibby LogSnag