Facebook Pixel
Recursive Problems and Solutions in JavaScript

How do you calculate factorial recursively in JavaScript?

The answer

function factorial(n) { if (n <= 1) return 1; return n * factorial(n - 1); }. Base case: 1 returns 1. Recursive case: n * factorial(n-1).

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

Want to upskill yourself?

Your learning library

Small steps. Big possibilities.

Find your next course. Build something great.

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.