Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function factorial(num) {
- return (num !== 1) ? num * factorial(num - 1) : 1;
- }
- /* Here's how it will work if we do a factorial(4);
- Each call: num === "?" num * factorialize(num - 1)
- 1st call – factorialize(4) will return 4 * factorialize(4 - 1) // 4 * factorialize(3)
- 2nd call – factorialize(3) will return 3 * factorialize(3 - 1) // 4 * 3 * factorialize(2)
- 3rd call – factorialize(2) will return 2 * factorialize(2 - 1) // 4 * 3 * 2 * factorialize(1)
- 4th call – factorialize(1) will return 1 // 4 * 3 * 2 * 1
- Now the function hits the abort-condition (num !== 1), so it returns 1
- 4 * 3 * 2 * factorialize(1) = 4 * 3 * 2 * 1 = 24
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement