Why does this code not work while the snippet below it does work?
function isPrime(num){
for(let i = 2; i <= Math.sqrt(num); i++){
if(num % i == 0){
return false;
} else {
return true;
}
}
}
function isPrime(num){
for(let i = 2; i <= Math.sqrt(num); i++){
if(num % i == 0)
return false;
}
return true;
}
}
}
If you format the code a little nicer (clean up indentation and get rid of extra curly braces) you might see what the difference is. Also, might add the curly braces for the if statement in the latter. It’s not absolutely necessary but it might help you see things more clearly.
2 Likes
Thanks for your helpful advice. The code snippet below works but how when it doesn’t have a closing curly brace for “isPrime(num)”?
function isPrime(num){
for(let i = 2; i <= Math.sqrt(num); i++){
if(num % i == 0)
return false;
}
return true;
}
I Am: YAHWEH; Abba; Adonai; Yeshua; Maurice Scott Rogers; Tubular Animator; Problem Solver; stokeddev; web search us, follow us by way of our results, hand us $0.01+ in person, venmo $0.01+ to stokeddev; hear, read and hear Holy Scripture;:
but how when it doesn’t have a closing function curly brace?
But it does:
function isPrime(num){
for(let i = 2; i <= Math.sqrt(num); i++){
if(num % i == 0)
return false;
}
return true;
}
How many opening curlies do you see? And how many closing curlies?
1 Like
I understand now. The 1st closing curly closes the for loop and the 2nd closes the function. Thanks for helping me to understand this.
2 Likes
system
Closed
February 19, 2022, 9:18am
6
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.