Shallow Copy
Object.assign copies properties from source objects into a target.
It performs a shallow copy, not a deep clone.
JavaScript Tutorial
Object.assign copies properties from one or more sources into a target object.
It is commonly used for shallow copies and merges.
Merging objects is common when combining defaults with user options.
Object.assign provides a simple built-in way to do that.
Object.assign(target, ...sources)const user = { name: "Ava" };
const copy = Object.assign({}, user);
console.log(copy);Copy into a new object.
const a = { name: "Ava" };
const b = { role: "admin" };
const merged = Object.assign({}, a, b);
console.log(merged);Combine multiple sources.
Object.assign copies properties from source objects into a target.
It performs a shallow copy, not a deep clone.
You can merge multiple sources into one target.
Later sources overwrite earlier properties.
Spread syntax is often more readable for simple merges.
Use structuredClone or libraries for deep copies.
const base = { role: "user" };
const next = Object.assign({}, base, { role: "admin" });
console.log(next);Later sources overwrite earlier ones.
const user = { profile: { city: "Pune" } };
const copy = Object.assign({}, user);
copy.profile.city = "Delhi";
console.log(user.profile.city); // DelhiNested objects are shared in shallow copies.
Without
const merged = { ...a, ...b };With
const merged = Object.assign({}, a, b);Object.assign is shallow; nested objects are shared.
Use {} as the target for a fresh copy.
Be mindful of source order.
Yes, it mutates the target object.
It performs a shallow copy.
When you need deep cloning or immutability.
Practice: Merge a defaults object with a user settings object.
const defaults = { theme: "light", layout: "grid" };
const user = { theme: "dark" };
// TODO: merge into a new object
One Possible Solution
const defaults = { theme: "light", layout: "grid" };
const user = { theme: "dark" };
const merged = Object.assign({}, defaults, user);
console.log(merged);No, it is a shallow copy.
Yes, it writes into the target object.
Spread syntax: { ...a, ...b }.
Try merging different objects and see results.