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;
}
```

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.