How to Deep Clone an Object in JavaScript Using a For Loop?

Estimated read time 1 min read

You can deep clone an object in JavaScript using a for loop by checking the type of each property in the original object and copying it to a new object. If the property is an object itself, you can call the deep cloning function recursively.

Here’s an example:

function deepClone(obj) {
  if (obj === null || typeof obj !== "object") {
    return obj;
  }

  let clone = Array.isArray(obj) ? [] : {};

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

  return clone;
}

const original = { a: 1, b: { c: 2 } };
const clone = deepClone(original);

This approach is more flexible and works for objects with properties of any type, including nested objects, arrays, functions, and so on.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply