How to clone an object? assign, spread operator, JSON.parse(JSON.stringify), Object.create, recursive traversal, structuredClone.

👨‍💻 Frontend Developer 🟡 Often Asked 🎚️ Medium
#JavaScript #Objects #JS Basics

Brief Answer

Object cloning in JavaScript is creating a copy of an object that doesn’t reference the original object in memory. There are several cloning methods, each with its own features: shallow or deep copying, support for different data types, and performance.

Main cloning methods:

  • Object.assign() — shallow copying
  • Spread operator — shallow copying
  • JSON.parse(JSON.stringify()) — deep copying with limitations
  • Object.create() — creating object with prototype
  • Recursive traversal — full deep copying
  • structuredClone — modern deep copying method

Full Answer

Object cloning is an important concept in JavaScript that allows creating independent copies of data. The correct method choice depends on copying depth requirements and data types in the object.

Shallow Copying Methods

1. Object.assign()

Copies only enumerable properties of the first level:

const original = { a: 1, b: { c: 2 } };
const copy = Object.assign({}, original);

2. Spread Operator

Modern syntax for shallow copying:

const copy = { ...original };

Deep Copying Methods

1. JSON.parse(JSON.stringify())

Simple deep copying method with limitations:

const deepCopy = JSON.parse(JSON.stringify(original));

2. Recursive Traversal

Full deep copying of all data types:

function deepClone(obj) {
  // Recursive copying implementation
}

3. structuredClone

Modern browser API for deep copying:

const deepCopy = structuredClone(original);

Practical Examples

Example with Nested Objects

const user = {
  name: 'John',
  address: {
    city: 'Moscow',
    street: 'Lenina'
  }
};
 
// Shallow copying
const shallow = { ...user };
shallow.address.city = 'Saint Petersburg';
// Original object will also change!
 
// Deep copying
const deep = structuredClone(user);
deep.address.city = 'Kazan';
// Original object won't change

Example with Arrays

const data = {
  items: [1, 2, { value: 3 }]
};
 
// Different methods give different results
const assignCopy = Object.assign({}, data);
const spreadCopy = { ...data };
const jsonCopy = JSON.parse(JSON.stringify(data));

Common Mistakes

1. Wrong Method Choice

// ❌ Using spread for deep copying
const config = {
  database: {
    host: 'localhost',
    port: 5432
  }
};
 
const copy = { ...config };
copy.database.host = 'remote'; // Will change original too!
 
// ✅ Using structuredClone for deep copying
const deepCopy = structuredClone(config);

2. Using JSON Methods with Incompatible Types

// ❌ JSON methods don't work with functions, undefined, Symbol
const obj = {
  func: () => {},
  undef: undefined,
  sym: Symbol('test'),
  date: new Date()
};
 
const copy = JSON.parse(JSON.stringify(obj));
// Functions, undefined and Symbol will be lost!
 
// ✅ Using structuredClone
const properCopy = structuredClone(obj);

Best Practices

  1. Use spread/Object.assign for simple objects — when there are no nested references
  2. Apply structuredClone for complex structures — modern and reliable method
  3. Avoid JSON methods with functions and special types — they’re lost during serialization
  4. Write custom functions for specific cases — when control over process is needed
  5. Check structuredClone support — polyfill needed for older browsers

Compatibility

  • Object.assign — ES6, supported by all modern browsers
  • Spread operator — ES6-ES9, depends on data type
  • JSON methods — supported by all browsers
  • Object.create — ES5, wide support
  • structuredClone — modern browsers (Chrome 98+, Firefox 94+)
  • Recursive traversal — works everywhere, manual implementation

Key Method Features

  1. Shallow copying — only first level, nested objects remain references
  2. Deep copying — all nesting levels, completely independent copy
  3. Performance — different methods have different speed
  4. Type support — not all methods work correctly with functions, dates, RegExp
  5. Memory — deep copying requires more resources

The correct cloning method choice depends on data structures, performance requirements, and supported browsers.


Knowledge Check Task

Task

What will be the result and why?

const original = {
  name: 'Test',
  data: {
    value: 42,
    nested: {
      flag: true
    }
  },
  tags: ['js', 'clone'],
  func: function() { return this.name; }
};
 
// Method 1
const copy1 = { ...original };
 
// Method 2
const copy2 = JSON.parse(JSON.stringify(original));
 
// Method 3
const copy3 = structuredClone(original);
 
// What will happen when changing?
copy1.data.value = 100;
copy2.tags[0] = 'javascript';
copy3.data.nested.flag = false;
 
console.log(original.data.value);
console.log(original.tags[0]);
console.log(original.data.nested.flag);
console.log(copy2.func);
View answer

Answer:

100
js
true
undefined

Explanation:

  1. copy1 (spread operator):

    • Shallow copying
    • copy1.data remains a reference to original.data
    • Changing copy1.data.value affects original.data.value
    • original.data.value becomes 100
  2. copy2 (JSON methods):

    • Deep copying, but with limitations
    • copy2.tags — independent array copy
    • Changing copy2.tags[0] doesn’t affect original.tags[0]
    • original.tags[0] remains ‘js’
    • copy2.func will be undefined, as functions are lost during JSON serialization
  3. copy3 (structuredClone):

    • Full deep copying
    • copy3.data.nested — independent copy
    • Changing copy3.data.nested.flag doesn’t affect original.data.nested.flag
    • original.data.nested.flag remains true

Error in analysis above — let’s reconsider:

Actually:

  • original.data.value will be 100 (changed via copy1)
  • original.tags[0] will remain ‘js’ (copy2.tags is independent copy)
  • original.data.nested.flag will remain true (copy3.data.nested is independent copy)
  • copy2.func will be undefined (functions are lost in JSON)

Correct result:

100
js
true
undefined

This example demonstrates important differences between cloning methods:

  • Shallow copying preserves references to nested objects
  • JSON methods lose functions, undefined, Symbol and special objects
  • structuredClone — most complete method, supporting all data types

Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪