Facebook Pixel

How do you reverse a string recursively in JavaScript?

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.

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 factorial(n) { if (n <= 1) return 1; return n * factorial(n - 1); }. Base case: 1 returns 1. Recursive case: n * factorial(n-1).

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

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
Please Login.
Please Login.
Please Login.