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
// function to check if a number is prime or not
function isPrimeNumber(number) {
// check if the passed value is a number
if (typeof number == 'number' && !isNaN(number)) {
if (number > 1) {
// looping through 2 to number-1
for (let i = 2; i < number; i++) {
if (number % i == 0) {
return false;
break;
}
}
return true;
}
}
return false;
}
isPrimeNumber('hello');
isPrimeNumber(44);
isPrimeNumber(3.4);
isPrimeNumber(5);
isPrimeNumber(-3.4);
isPrimeNumber(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 👍.