Object.assign use cases

Andrea Giammarchi
2 min readJan 9, 2021

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.

const data = {};
Object.assign(data, {other: "data"}, {and: "more"});
data;
// {other: "data", and: "more"}

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

const data = Object.assign({nough: 1}, {moar: "data"});
data;
// {nough: 1, moar: "data"}

How else can we use Object.assign?

Every single time we write something like this:

const stuff = somethingToConfigure();
stuff.onclick = () => { /* something meaningful */ };
stuff.onerror = () => { /* something meaningful */};

we could refactor it via Object.assign:

const stuff = Object.assign(somethingToConfigure(), {
onclick() { /* something meaningful */ },
onerror() { /* something meaningful */ }
});

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:

// Web Worker
const worker = Object.assign(new Worker(path), {
onmessage(event) {}
});
// 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:

const cool = Object.assign({}, behavior1, behavior2);

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 🥳

--

--

Andrea Giammarchi

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