DEV Community

Usama
Usama

Posted on

πŸ’‘ Mastering `Object.assign()` in JavaScript

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

Enter fullscreen mode Exit fullscreen mode

🟠 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 }

Enter fullscreen mode Exit fullscreen mode

πŸ’‘ 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" }

Enter fullscreen mode Exit fullscreen mode

⚑ 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)

Enter fullscreen mode Exit fullscreen mode

βœ… 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 }

Enter fullscreen mode Exit fullscreen mode

⚠️ 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)