Object.assign() in JavaScript

Jul 30, 2019

In JavaScript, the Object.assign() function copies properties from one or more source objects to a target object. It returns the target object.

const source = { hello: 'world' };
const target = {};

// The first parameter is the target object, every subsequent parameter
// is a source object.
const ret = Object.assign(target, source);

// `Object.assign()` modifies `target` in place, and returns `target`
ret === target; // true
target.hello; // 'World'

Object.assign() is commonly used to shallow copy objects, although the spread operator is generally faster than Object.assign() for shallow copying. Shallow copying is most commonly used in Redux reducers.

const obj = { name: 'Jean-Luc Picard', age: 59 };

// `Object.assign({}, obj)` is a common pattern that returns a shallow
// clone of `obj`.
const shallowCopy = Object.assign({}, obj);

shallowCopy === obj; // false

// Cloning the object means that changing `shallowCopy` doesn't affect `obj`
shallowCopy.rank = 'Captain';
obj.rank; // undefined

Multiple Sources

You can pass multiple source objects to Object.assign(). If there's multiple sources with the same property, the last one in the parameter list wins out.

const o1 = { a: 1, b: 1, c: 1 };
const o2 = { a: 2, b: 2 };
const o3 = { a: 3 };

Object.assign(o1, o2, o3); // { a: 3, b: 2, c: 1 }

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!