Factorial multiplication in javascript
function factorial(n) { if (n == 1) { return 1; } return n * factorial(n - 1); } console.log(factorial(6)); //Output: 720
Here is what the above code is Doing:
1. The function is called with the argument 6.
2. The function calls itself with the argument 5.
3. The function calls itself with the argument 4.
4. The function calls itself with the argument 3.
5. The function calls itself with the argument 2.
6. The function calls itself with the argument 1.
7. The function returns 1.
6. The function returns 2 * 1.
5. The function returns 3 * 2.
4. The function returns 4 * 6.
3. The function returns 5 * 24.
2. The function returns 6 * 120.
1. The function returns 720.