How do you deep clone an object recursively in JavaScript?
function deepClone(obj) { if (obj === null || typeof obj !== 'object') return obj; const clone = Array.isArray(obj) ? [] : {}; Object.keys(obj).forEach(key => clone[key] = deepClone(obj[key])); return clone; }
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Recursion: Real-World Applications in JavaScript
JSON tree rendering (recurse on values), file explorer (recurse on children), nested comments (recurse on replies), deep clone (recurse on object properties), and DOM traversal (recurse on childNodes). Any nested or self-similar structure.
function renderComment(comment, depth) { /* render comment */ comment.replies.forEach(reply => renderComment(reply, depth + 1)); }. Each comment recurses into its replies, indenting by depth.
function search(node, text, results = []) { if (node.textContent.includes(text)) results.push(node); node.children.forEach(child => search(child, text, results)); return results; }. Recurse into children and accumulate matches.
Still have questions?
Browse all our FAQs or reach out to our support team
