Object.assign()

ES6+

Copies all enumerable own properties from one or more source objects to a target object.

Syntax

Object.assign(target, ...sources)

Parameters

target Object

The target object to copy to

sources Object

The source object(s) to copy from

Return Value

Object

The target object

Examples

JavaScript
const target = { a: 1 };
const source = { b: 2, c: 3 };
const result = Object.assign(target, source);
console.log(result);
Output:
// { a: 1, b: 2, c: 3 }

📌 When to Use

Use Object.assign() for shallow copying objects, merging multiple objects into one, or adding properties to an existing object. It is commonly used for creating config objects with defaults, cloning objects, or implementing simple mixin patterns.

⚠️ Common Mistakes

Expecting deep cloning - Object.assign() only does shallow copy. Nested objects are copied by reference, not cloned.

Forgetting that the first argument (target) is modified - if you want a new object, always use an empty object as the first argument.

Not handling null or undefined sources - Object.assign() skips null/undefined sources, but this silent behavior can mask bugs.

✅ Best Practices

Prefer spread syntax {...obj} for simple cloning in modern code - it is more readable and commonly understood.

Use Object.assign({}, defaults, userOptions) pattern for merging defaults with user-provided options.

For deep cloning, use structuredClone() (modern browsers) or JSON.parse(JSON.stringify(obj)) for JSON-safe objects.

⚡ Performance Notes

Object.assign() has O(n) complexity where n is the total number of properties across all source objects. Spread syntax {...obj} has similar performance but may be slightly faster in modern engines. For frequent object copying in hot paths, consider object pooling or immutable data structures like Immer.

🌍 Real World Example

API Request Configuration Builder

Build API request configurations by merging default settings with endpoint-specific options using Object.assign().

const defaultConfig = {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  timeout: 5000,
  retries: 3
};

function createRequest(url, options = {}) {
  // Merge defaults with user options
  const config = Object.assign({}, defaultConfig, options, { url });

  // Handle nested headers separately (shallow copy issue)
  config.headers = Object.assign({}, defaultConfig.headers, options.headers);

  return config;
}

const getUsers = createRequest('/api/users');
console.log(getUsers);
// { method: 'GET', headers: {...}, timeout: 5000, retries: 3, url: '/api/users' }

const createUser = createRequest('/api/users', {
  method: 'POST',
  headers: { 'Authorization': 'Bearer token123' },
  timeout: 10000
});
console.log(createUser.method); // 'POST'
console.log(createUser.headers);
// { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': 'Bearer token123' }

Related Methods