Q15: Implement a polyfill for Object.assign().

Difficulty:IntermediateTopic:Object Methods

Answer

Object.assign() copies enumerable own properties from one or more source objects into a target object. It returns the target object and performs a shallow copy.

if (!Object.myAssign) {
  Object.myAssign = function (target, ...sources) {
    if (target == null) {
      throw new TypeError("Cannot convert undefined or null to object");
    }

    const output = Object(target);

    for (const source of sources) {
      if (source == null) {
        continue;
      }

      const from = Object(source);

      for (const key of Reflect.ownKeys(from)) {
        const descriptor = Object.getOwnPropertyDescriptor(from, key);

        if (descriptor && descriptor.enumerable) {
          output[key] = from[key];
        }
      }
    }

    return output;
  };
}

const target = { a: 1 };
const source = { b: 2 };

console.log(Object.myAssign(target, source));
// { a: 1, b: 2 }

Explanation

  1. Reject a nullish target.
  2. Convert the target into an object.
  3. Process each source object.
  4. Read its own property keys, including symbols.
  5. Copy enumerable properties to the target.
  6. Return the target object.

Interview notes

Object.assign() is shallow: nested objects remain shared references. It reads source property values and writes to the target, so getters and setters can execute. A production implementation should preserve native error and property-copy semantics carefully.

Key Takeaways
  • Object.assign copies enumerable own properties and returns the target.
  • The copy is shallow, and symbol properties can also be copied.