A shallow copy of an object in JavaScript creates a new object with the same properties as the original object. However, the values of those properties are references to the same underlying data as the original object. This means that changes made to the copied object's properties will also affect the original object.
Here are two common ways to make a shallow copy of an object in JavaScript:
1. Using the Spread Operator (...
)
The spread operator can be used to create a new object with the same properties as the original object. This method is concise and easy to understand.
Example:
const originalObject = { name: "John", age: 30 };
const shallowCopy = { ...originalObject };
shallowCopy.name = "Jane";
console.log(originalObject); // Output: { name: "Jane", age: 30 }
console.log(shallowCopy); // Output: { name: "Jane", age: 30 }
2. Using Object.assign()
The Object.assign()
method can be used to copy properties from one object to another. You can use it to create a shallow copy by passing an empty object as the first argument and the original object as the second argument.
Example:
const originalObject = { name: "John", age: 30 };
const shallowCopy = Object.assign({}, originalObject);
shallowCopy.name = "Jane";
console.log(originalObject); // Output: { name: "Jane", age: 30 }
console.log(shallowCopy); // Output: { name: "Jane", age: 30 }
Note: Both methods create a shallow copy, so any nested objects within the original object will be shared by reference between the original and the copied object. Changes to these nested objects will affect both the original and the copied object.