Factorialize A Number: "Out of scope" question

Hello! First post here…

I seem to keep having a misunderstanding of whether to put things inside or outside of curly brackets. Could someone provide a good explanation of the difference in these two codes, particularly why “return result;” only works outside the brackets?

This works:

function factorialize(num) {
  var result = num;
  if(num===0){
    return 1;
  }
  while(num>1){
    num--;
    result=result*num;
    }
    return result;
}
factorialize(5);

This does not work:

function factorialize(num) {
  var result = num;
  if(num===0){
    return 1;
  }
  while(num>1){
    num--;
    result=result*num;
    return result;
    }
    
}
factorialize(5);

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

Oops… newbie mistake. Thanks

As soon as a return statement is hit in code, the function is exited. In your non-working example, the return statement is inside the loop. That means that the return statement is hit after result=result*num occurs the first time. In your working example the return isn’t hit until the loop is done looping.

Thank you. That was extremely helpful.