If conditional curly braces and else

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

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.