Javascript Interview Question: Write a function which deep clones a object

Building a Comprehensive Function for Deep Object Cloning

Deep Ocean

In JavaScript, objects and arrays are reference types, which means that when you assign one variable to another, you’re actually copying a reference to the original object or array, not creating a new independent copy. This can lead to unexpected behavior if you modify the contents of the object or array through one reference, as it will affect all other references pointing to the same object.

A deep clone function is used to create a completely independent copy of an object or array, including all nested objects and arrays.

function deepClone(obj) {
if (obj === null || typeof obj !== 'object') {
return obj; // Base case: return primitive types or null
}

if (Array.isArray(obj)) {
// If it's an array, clone each element
return obj.map((item) => deepClone(item));
}

// If it's an object, clone each property (including nested objects and arrays)
const clonedObj = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
clonedObj[key] = deepClone(obj[key]);
}
}

return clonedObj;
}

// Example usage:
const originalObject = {
name: 'John',
age: 25,
hobbies: ['reading', 'coding'],
address: {
city: 'Example City',
zip: '12345',
},
};

const clonedObject = deepClone(originalObject);

console.log(clonedObject);

Let’s break it down:

  1. Let’s start by defining our function and Base Case
    The function begins with a base case. If the input is a primitive type or null, the function returns the input as it is not necessary to clone these values.
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
// …
}

2. Handling Arrays

if (Array.isArray(obj)) {
return obj.map((item) => deepClone(item));
}

If the input is an array, we use the `map` function to iterate over each element, recursively calling `deepClone` for each item. This ensures that arrays within the object are also cloned deeply.

3 Handling Objects

const clonedObj = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
clonedObj[key] = deepClone(obj[key]);
}
}
return clonedObj;

If the input is an object, we create a new object (`clonedObj`) and iterate over each property. For each property, we recursively call `deepClone` to handle nested structures.

4. Usage

const originalObject = {
name: 'Spider',
age: 25,
hobbies: ['swinging', 'walking'],
address: {
city: 'Brooklyn',
zip: 'karo',
},
};
const clonedObject = deepClone(originalObject);
console.log(clonedObject);

Conclusion: Although this answer might help you in clearing your interview, but avoid it using in production application.In Production applications prefer structuredClone or loadash’s clone deep method.

--

--