JavaScript Practice: Arrays, Loops, Objects, Iterators - Factorial

Hello guys, I’m doing the factorial exercise in this linkJavaScript Practice: Arrays, Loops, Objects, Iterators

If I use ‘return’ inside the ‘for loop’, the output is 30. See below

const factorial = num => {
  for (i = num -1; i >= 1; i--) {
    return num *= i
  }
}

console.log(factorial(6))
//output 30

If I use ‘return’ after the ‘for loop’, the output is 720 which is the correct answer. See below:

// Write function below
const factorial = num => {
  for (i = num -1; i >= 1; i--) {
    num *= i
  }
  return num
}

console.log(factorial(6))
//output 720

Why is that?

Hello! When you use return, all code after it that is still inside the function is not executed. Example:

function x(){
  console.log("Hello");
  return "World";
  console.log("!");
}
x();
//output: "Hello"

The ! isn’t outputted because once a return is met, the function stops there.


The same thing is happening with your factorial function. After the first iteration of the for loop: 6*(6-1) = 6*5 = 30, a return is met, which ends the function, and hands the data (30) back to the caller.

I hope this helps!

Thanks for your reply.

I see. So it’s like break. It stops the loop

1 Like