How do you calculate factorial recursively in JavaScript?
function factorial(n) { if (n <= 1) return 1; return n * factorial(n - 1); }. Base case: 1 returns 1. Recursive case: n * factorial(n-1).
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Recursive Problems and Solutions in JavaScript
function flatten(arr) { return arr.reduce((acc, item) => acc.concat(Array.isArray(item) ? flatten(item) : item), []); }. If an item is an array, recurse. Otherwise, concatenate.
function traverse(node, callback) { callback(node); if (node.children) node.children.forEach(child => traverse(child, callback)); }. Call the callback on the current node, then recurse into each child.
function reverse(str) { if (str.length <= 1) return str; return reverse(str.slice(1)) + str[0]; }. Take the first character, reverse the rest, and append the first character at the end.
Still have questions?
Browse all our FAQs or reach out to our support team
