Cloning a JavaScript object can be achieved through various methods, each suitable for different scenarios:
Shallow Copy with Spread Operator (...):
Creates a new object by copying enumerable properties from the source object.
This method performs a shallow copy; nested objects remain linked to the original.
Example:
const original = { a: 1, b: { c: 2 } };
const clone = { ...original };
console.log(clone); // { a: 1, b: { c: 2 } }
Deep Copy with structuredClone():
Creates a deep clone of a given value using the structured clone algorithm.
Example:
const original = { a: 1, b: { c: 2 } };
const clone = structuredClone(original);
console.log(clone); // { a: 1, b: { c: 2 } }