You are very close. I will build on top of your solution. You need to return false as soon as you detect that the number is not prime. This avoids us making additional redundant calculations.
You also did not take into account the first hint.
Hint - Note: 0 and 1 are NOT considered prime numbers
For this you can simply return false
if number is 0 or 1.
function isPrime(num) {
if (num === 0 || num === 1) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}
Also in your code you are using a variable isPrime to keep track of boolean values while initialising it with an empty string. This is not correct. Javascript allows this because it's weakly typed, but this is misleading. So in future if you define a variable for boolean value don't initialise it with a string ;)
To address your comment further. If you do want to stick with having a flag in your code, then you can initialise isPrime with true instead of an empty string.
That way you can get rid of the else part in the for loop, making the code shorter. I used code provided by @Commercial Suicide (by the way he did say that there are more elegant solutions) as an example:
function isPrime(num) {
let flag = true;
let isPrime = true;
if (num === 0 || num === 1) return false;
if (num === 2) return true;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (flag) {
if(num % i === 0) {
isPrime = false;
flag = false;
}
}
}
return isPrime;
}
const numbers = [1, 7, 11, 15, 20];
const booleans = [false, true, true, false, false];
numbers.forEach((item, i) => {
if (isPrime(item) === booleans[i]) {
console.log("CORRECT");
} else {
console.log("WRONG");
}
})
You can then go a step further and remove the flag variable.
function isPrime(num) {
let isPrime = true;
if (num === 0 || num === 1) return false;
if (num === 2) return true;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (isPrime) {
if(num % i === 0) {
isPrime = false;
} else {
isPrime = true;
}
}
}
return isPrime;
}
But now it should become even more clear that those flags are actually redundant, as I pointed out initially. Simply return false as soon as you detect that the number is not prime to avoid further unnecessary loop runs. From my experience in javascript over the years I can see that we are heading towards functional programming mindset. It helps to avoid variable mutations generally.