Objects are super powerful in JavaScript.
Sometimes we need to copy values from one object to another or merge multiple objects together.
Thatβs where π Object.assign()
comes in!
π’ What is Object.assign()
?
Itβs a built-in method that copies properties from one or more source objects into a target object.
Syntax:
Object.assign(target, ...sources)
target β the object where data will be copied into
sources β one or more objects to copy from
π Example 1: Simple Copy
const user = { name: "Ali" };
const extra = { age: 25 };
const result = Object.assign({}, user, extra);
console.log(result);
// π { name: "Ali", age: 25 }
π‘ We used an empty object {} as the target, so both user and extra got merged into it.
π Example 2: Overwriting Properties
If the same property exists in multiple objects, the last one wins (it overwrites).
const obj1 = { skill: "React" };
const obj2 = { skill: "Node.js" };
const merged = Object.assign({}, obj1, obj2);
console.log(merged);
// π { skill: "Node.js" }
β‘ The value from obj2 replaced the value from obj1.
π Example 3: Cloning an Object
We can make a shallow copy of an object like this:
const original = { city: "Lahore" };
const clone = Object.assign({}, original);
console.log(clone);
// π { city: "Lahore" }
console.log(original === clone);
// π false (different objects in memory)
β The clone has the same data but is a different object in memory.
π Example 4: Multiple Sources
const a = { x: 1 };
const b = { y: 2 };
const c = { z: 3 };
const all = Object.assign({}, a, b, c);
console.log(all);
// π { x: 1, y: 2, z: 3 }
β οΈ Limitations
It only makes a shallow copy (nested objects are still references).
For deep copies, use structuredClone() or libraries like Lodash.
π― Final Thoughts
Object.assign() is a simple but powerful tool:
β Merge objects
β Create shallow copies
β Set default values
Keep this handy whenever youβre working with objects in JavaScript β¨
π Have you ever used Object.assign() in your projects?
Drop a comment and share your experience π
Top comments (0)