In this era of AI generated code, you will see some logic generated by AI. An example of such is, Object.assign()
. So if you have also come across this and don’t know what it means, this article aims to do justice to that. Let’s dive into it.
In modern JavaScript, a few methods quietly do the heavy lifting behind the scenes. One of those method is Object.assign()
. While it might not have the flair of new syntax or frameworks, it plays a critical role in data manipulation, state management, and object composition. Note the Object composition.
By the end of this article, you should know what Object.assign() is, how it works, what it’s good for and where it can bite you if you’re not careful.
What Exactly Is Object.assign()
?
Introduced in ECMAScript 2015 (ES6), Object.assign()
is a static method on the global Object constructor. Its job is simple but powerful, it is meant to: copy the values of all enumerable own properties from one or more source objects to a target object.
Here’s the basic syntax:
Object.assign(target, ...sources)
- target: The object that will receive the properties.
- sources: One or more source objects whose properties will be copied.
The method returns the modified target object.
Let’s observe some examples.
Example: Cloning and Merging
const target = { a: 1 };
const source = { b: 2, c: 3 };
const result = Object.assign(target, source);
console.log(result); // { a: 1, b: 2, c: 3 }
console.log(target === result); // true
Here, source’s properties are copied into target, and target is returned. Object.assign() is destructive in the sense that it modifies the first argument.
Use Case 1: Shallow Cloning
If you need a quick way to clone an object, then Object.assign()
works, but that also depends on if you’re okay with a shallow copy like this.
const obj = { a: 1, b: { nested: true } };
const clone = Object.assign({}, obj);
clone.b.nested = false;
console.log(obj.b.nested); // false (Oops!)
Because Object.assign()
only copies property references for nested objects, changes to nested data in the clone affect the original. For deep cloning, consider structuredClone()
or libraries like Lodash
.
Use Case 2: Merging Multiple Objects
If you are merging or combining configurations, settings, or component props, Object.assign()
also will work for you. Consider this example.
const defaultSettings = { theme: 'light', debug: false };
const userSettings = { debug: true };
const finalSettings = Object.assign({}, defaultSettings, userSettings);
// { theme: 'light', debug: true }
The order matters later parameters override earlier ones. This is great for applying defaults and then overwriting with user-specific values.
Pitfalls and Cons
1. Shallow Copying Only
As mentioned, nested objects are not deeply copied. This limitation can cause unintended side effects if you’re not careful. So now you know for next time you encounter this when vibe-coding or otherwise.
2. Enumerability
Only enumerable properties are copied. That means properties set with Object.defineProperty()
using enumerable: false
won’t be included.
const obj = {};
Object.defineProperty(obj, 'hidden', {
value: 'secret',
enumerable: false
});
const copy = Object.assign({}, obj);
console.log(copy.hidden); // undefined
3. No Prototype Transfer
Object.assign() does not copy over an object’s prototype chain. It only deals with own properties.
How Object.assign()
Works
Internally, Object.assign()
performs the following steps:
- Converts target to an object (if it’s not already).
- Iterates over the source objects from left to right.
- For each source:
- Converts it to an object.
- Loops through its own enumerable properties (both string and symbol keys).
- Copies each property to the target.
- Returns the modified target.
This behavior is consistent with the ECMAScript specification and helps developers predict its effects.
In case this seems too difficult to understand or you simply wish there were simpler alternatives to using Object.assign()
. The answer is that there are. Let’s consider some alternatives.
Alternatives to Object.assign()
1. Spread Operator (...)
In many cases, the spread syntax is a cleaner alternative:
const merged = { ...defaultSettings, ...userSettings };
It’s more concise and often easier to read, especially when cloning or merging.
However, the spread operator is syntactic sugar, it’s not identical. Notably, it doesn’t copy symbol properties or getters/setters.
2. structuredClone()
structuredClone exists for deep cloning. Consider this:
const deepCopy = structuredClone(obj);
This handles nested structures, dates, arrays, and more. Something Object.assign()
can’t do. So if there are certain copy Object.assign()
cannot handle, when do we use Object.assign()
?
When to Use Object.assign()
Use Object.assign()
when:
- You need to merge objects with potential fallback values.
- You’re working in an environment without spread syntax support.
- You need fine control over property copying (e.g., including symbols).
And, Avoid it when:
- You need deep cloning.
- You’re dealing with objects that include non-enumerable or getter/setter properties.
Some Real-World Applications
In frontend frameworks like React or Vue, Object.assign()
often powers state updates, prop merging, and configuration layering.
In Node.js though, you’ll find it in utility libraries, plugin loaders, and even Express middleware that combines options.
It’s ubiquity makes it a tool every JavaScript developer should know inside and out.
Final Thoughts
Object.assign()
isn’t flashy, but it’s reliable and versatile. Whether you’re merging configs, copying objects, or applying fallbacks, this method gives you precise control over object manipulation, that is if you understand its rules.
But Mastering Object.assign()
will help you write cleaner, more predictable JavaScript. Just remember that with great power comes shallow copying.
If you enjoyed reading this article, give a like, clap or any reaction.
If you have questions or additions or comments, Drop a comment, I’d love to hear from you.
If you want to learn more uncommon JavaScript methods. Check out my other articles. I’m sure you’ll see other contents that interests you.
Thank you for reading. 🙂
Top comments (0)