Hi Friends đź‘‹,
Welcome To Infinitbility! ❤️
To check number is a prime number, looping through 2 to your given number-1 and check is any divisible number or not, if have means it’s not a prime number.
Note: 1 is considered neither prime nor composite.
Today, I’m going to show How do I check if the number is a prime number or not in Javascript, here I will create a custom function isPrimeNumber()
where I will check if there have any divisible number based on this it will return a boolean value.
Let’s start the today’s tutorial How do you check if the number is prime in JavaScript?
In the following example
- check given value is a number
- check given value is greater than 1
- check given value is prime or not
1// function to check if a number is prime or not2function isPrimeNumber(number) {3 // check if the passed value is a number4 if (typeof number == 'number' && !isNaN(number)) {5 if (number > 1) {6 // looping through 2 to number-17 for (let i = 2; i < number; i++) {8 if (number % i == 0) {9 return false;10 break;11 }12 }13 return true;14 }15 }16 return false;17}1819isPrimeNumber('hello');20isPrimeNumber(44);21isPrimeNumber(3.4);22isPrimeNumber(5);23isPrimeNumber(-3.4);24isPrimeNumber(NaN);
In the above program, we have taken examples of every possible value like parameter if string, number, positive value, a negative value, or NaN values. let’s check the output.

I hope it’s help you, All the best 👍.
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.