Published in


JavaScript Polyfill: Object.assign()

Interview Question

As we know, Polyfill is the most asked question in the interviews, and Object.assign() is one of them.

First, we need to understand, what Object.assign() do and where we can use it?

Object.assign() copies the values (of all enumerable own properties) from one or more source objects to a target object.

Ex: Object.assign(target, …sources)

const obj = { a: 1 };
const copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }

and now will see where we usually use

  • where ever we want to shallow copy the object so that it won't affect the parent object.
  • one of the core principles of Redux is to never mutate state, you’ll often find yourself using Object. assign() to create copies of objects with new or updated values.

Now we will implement Polyfill of Object.assign(),

  • target is the place where all source1, source 2 will get merge or overide the property.
  • nextSource is source1, source2…. we give in the second parameter of Object.assign
  • we need to use for loop to loop through all sources(source1, source2, …)
  • To loop through, we will use arguments whose starting index is 1.
  • new for loop to copy the all sources property to newTo object
  • and finally, we will return newTo object, where we will have all the property of source1, source2, …etc.


Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter



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