Functions Declartions? Confused?


#1
  if((n === 0) || (n === 1)) {
  return 1;
} else {
  return (n * factorial( n - 1)); //// can someone explain this part of this code??  i had to hint this part of this code?
}
}
factorial(10);

#2

its recursion, as explained here:

the syntax is maybe partial python, but the idea is the same

the function calls its self with one less (n-1) until base case (if((n === 0) || (n === 1))) is reached


#3

still little confused , but im getting it


#4

yea, its confusing to see the function call itself, and then once base case is reached to travel upwards again.

10 is an high number, lets do something lower:

function factorial(n){
  if((n === 0) || (n === 1)) {
  return 1;
} else {
  return (n * factorial( n - 1)); //// can someone explain this part of this code??  i had to hint this part of this code?
}
}
factorial(3);

then the first function call (last line of code) results in:

return (3 * factorial( 3 - 1));

now factorial( 3 - 1) needs to be called fist before return (3 * factorial( 3 - 1)); can returned so then you get:

return (2 * factorial( 2 - 1));

again, before this result can be returned factorial( 2 - 1) needs to be called, given that will result in n=1, we reach the base case:

if((n === 0) || (n === 1)) {
  return 1;
}

good, now we can travel backup. so we left here:

return (2 * factorial( 2 - 1));

factorial( 2 - 1) is now resolved to 1 (thanks to if condition known as base case):

return ( 2 * 1)

so now this is resolved:

return (3 * factorial( 3 - 1));

factorial( 3 - 1) returns 2, remember? return ( 2 * 1) ?

so now we can solve return (3 * factorial( 3 - 1));:

return 3 * 2

we solved it :smiley:


#5

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