Fix the Deep Clone Function
HardChallenge 10 of 20
Fix the Deep Clone Function
HardThis deep clone function is supposed to create a complete copy of an object, but it has bugs. Fix the implementation to handle all cases correctly.
Challenge 10 of 20
80 XP
Community Solutions
ObjectsRecursionDeep CopyJavaScript
Exit ChallengeTest Cases
0/2 passingTest Case #1
Input: deepClone({ a: 1, b: { c: 2 } })
Expected: { a: 1, b: { c: 2 } } (with no reference to original)
Run tests to see results
Test Case #2
Input: deepClone([1, [2, 3], { a: 4 }])
Expected: [1, [2, 3], { a: 4 }] (with no reference to original)
Run tests to see results
solution.js
1
<span class="token keyword">function</span> deepClone(obj) {
<span class="token keyword">if</span> (obj === <span class="token boolean">null</span> || <span class="token keyword">typeof</span> obj !== <span <span class="token keyword">class</span>="token number">039</span>;object<span <span class="token keyword">class</span>="token number">039</span>;) {
<span class="token keyword">return</span> obj;
}
<span class="token keyword">const</span> copy = Array.isArray(obj) ? [] : {};
<span class="token keyword">for</span> (<span class="token keyword">const</span> key in obj) {
copy[key] = obj[key];
}
<span class="token keyword">return</span> copy;
}Console
Run your code to see output here