Function Expression (Factorial)


#1

<PLEASE USE THIS TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/en/courses/learn-javascript-functions/lessons/functions/exercises/function-expressions

<Below this line, in what way does your code behave incorrectly? Include ALL error messages.>
What’s the difference between these two:

return (n * (n - 1));

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

Also, the exercises Function Declaration and Function Expression let me pass even using just (n - 1). It was only after I saw the “hints” section that I realized there was code missing.

```

const factorial = (n) => {
if ((n === 0) || (n === 1)) {
return 1;
}
else {
return (n * factorial(n - 1));
}
};

console.log(factorial(10));

<do not remove the three backticks above>

#2

Does the lesson expect us to use recursion? (Please post a link to the exercise. Thanks.)

Let n equal 7. The above will return 42.

This one will return 5040 after filling the call stack with 7 returns. When the base case is reached, recursion stops and the stack winds down. That is when the multiplication takes place. Notice the base case returns 1, and not a function call. That is the signal to wind down the stack.


#3

What’s recursion? Link posted.


#4

When a function calls itself. In the above we call the function with a value for n The return is,

return n * factorial(n - 1)

On the first return, the expression, 7 * factorial(6) goes into the call stack. On the second return, 6 * factorial(5) goes into the stack. This repeats until we get to the base case, return 1.

Winding down the stack we get 1 * 2 * 3 * 4 * 5 * 6 * 7 which gives, 5040.

The funny thing is that I predicted this quesiton would come up while beta testing the new course module.

https://www.startpage.com/do/dsearch?query=recursion


#5

Let me see if I got this right. The “factorial” part of “factorial(n - 1)” is not a reference to the name of the current function I wrote but it’s like another sort of built-in function that works by filling the call stack with multiple returns?


#6

It is in fact a reference to the same function, but with a different argument. Rather than return to the caller, it gets held in abeyance in the call stack. That is the internal object, a dedicated part of memory reserved for this purpose.


Here is another example to study…

function digit_sum(n) {
    if (n === 0) {
        return 0;                                      // base case
    } else {
        return n % 10 + digit_sum(Math.floor(n / 10)); // recursive case
    }
}

console.log(digit_sum(123456789));    // -> 45

It is written in ES5, but can be easily refactored to an ES6 arrow function.


#7

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