Object.assign~ Browser APIs ~

Object.assign

There are some APIs that I use frequently. Object.assign is one of them. For me, the use case is almost always constructing a new object by merging various properties. Here are the basics:

const skills = { JavaScript: true, GraphQL: false };
const user = { name: 'Krasimir' };

const profile = Object.assign({}, user, skills);
// { "name":"Krasimir", "JavaScript":true, "GraphQL":false }

There are a couple of aspects that make this method useful. We can, for example set a default value of a field and then overwrite it:

const defaults = { JavaScript: false, GraphQL: false, name: 'unknown' };
const skills = { JavaScript: true };

const profile = Object.assign(defaults, skills);
// { "JavaScript":true, "GraphQL":false, "name":"unknown" }

The assign method ignores the falsy arguments, so we can add a field only if it exists with a neat one-liner:

function createUser(accessToken) {
  const user = Object.assign(
    { name: "Krasimir" },
    accessToken && { accessToken }
  );
  return user;
}

createUser('xxx'); // { name:"Krasimir", accessToken:"xxx" }
createUser(); // { name:"Krasimir" }

Overall, I use this API as a safety net, especially when data is missing or incomplete.