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.

const data = {};
Object.assign(data, {other: "data"}, {and: "more"});
// {other: "data", and: "more"}
const data = Object.assign({nough: 1}, {moar: "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 */};
const stuff = Object.assign(somethingToConfigure(), {
onclick() { /* something meaningful */ },
onerror() { /* something meaningful */ }
// 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) {}
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.

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