Javascript shallow cloning
Created By: chatGPT
In JavaScript, shallow cloning creates a new object that is a copy of the original object. However, it only copies properties that are at the first level. If those properties are objects themselves, they are not cloned; instead, references to the original objects are copied. This means changes to nested objects in the cloned version will reflect in the original object.
const original = {
name: 'John',
age: 30,
address: {
city: 'New York',
zip: 10001
}
};
const shallowClone = { ...original };
// Modify the address in the shallow clone
shallowClone.address.city = 'Los Angeles';
console.log(original.address.city); // 'Los Angeles' - Original is affected
Methods to perform shallow cloning in JavaScript include using the spread operator,
Object.assign()
, and Array.prototype.slice()
for arrays. Each of these techniques has its own use cases depending on whether you're working with objects or arrays.const obj1 = { a: 1, b: 2 };
const clone1 = { ...obj1 }; // Spread operator
const obj2 = Object.assign({}, obj1); // Object.assign method
const array = [1, 2, 3];
const cloneArray = array.slice(); // Array slice method
In conclusion, shallow cloning is useful for quickly duplicating objects and arrays when you are sure that nested objects do not need to be cloned. Always be cautious about mutating nested properties in shallow clones, as this will impact the original object.
const originalArray = [1, 2, { a: 3 }];
const shallowCloneArray = [...originalArray];
shallowCloneArray[2].a = 4;
console.log(originalArray[2].a); // 4 - Original is affected