Object.assign use cases

While most developers use this utility to enrich object literals and data, in more than one occasion I’ve found myself loving its usage elsewhere.

What does Object.assign do?

Well, the short answer is that it copies one or more objects properties to its very first argument, but that’s a boring story.

It also returns the very first argument, so that creating a fresh new object with one or more extra properties is “easy-peasy”:

How else can we use Object.assign?

Every single time we write something like this:

we could refactor it via Object.assign:

As example, if we own an instance and we don’t leak it anywhere else, we can always attach DOM Level 0 events with ease:

// DOM Element
Object.assign(document.documentElement, {
onclick() {},
onkeypress() {}
// IndexedDB
Object.assign(idb.open(name, 1), {
onupgradeneeded({target: {result: db}}) {},
onsuccess({target: {result: db}}) {},
onerror(event) {}

And so on and so forth … keeping in mind shared properties can be defined once, so that to instrument anything we’ll go like mixins:

That’s it, really!

…. but … we need to keep in mind Object.assign flattens out accessors, so that getters become an own property, and non enumerable properties are not passed over.

However, if we’re cool with it, and we use it only to quickly enrich well known references with well known properties, I find it extremely useful, and I’ve used it extensively just recently, and felt super good about it 🥳

Web, Mobile, IoT, and all JS things since 00's. Formerly JS engineer at @nokia, @facebook, @twitter.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store