I am getting if and else both results from my JS Code even after using flags and break. What seems to be the possible reason?
function myFunction(){
let x = document.getElementById("int").value;
const rootx = Math.sqrt(x);
let textx = "";
let isPrimeX = true;
//checking the prime of x input
for (let i = 2; i<=rootx; i++){
if(x % i === 0 || x<=1 || x>2){
textx += x + " is not a prime number"
let isPrimeX = false;
break;
}
}if(isPrimeX == true){
textx += x + " is a Prime Number";
}
document.getElementById('demo').innerHTML = textx;
}
>Solution :
you are redeclaring isPrimeX
just remove let like this
function myFunction(){
let x = document.getElementById("int").value;
const rootx = Math.sqrt(x);
let textx = "";
let isPrimeX = true;
//checking the prime of x input
for (let i = 2; i<=rootx; i++){
if(x % i === 0 || x<=1 || x>2){
textx += x + " is not a prime number"
isPrimeX = false;
break;
}
}if(isPrimeX == true){
textx += x + " is a Prime Number";
}
document.getElementById('demo').innerHTML = textx;
}