Table of contents
1.
Introduction
2.
Description  
3.
How Does `Object.assign` Work?  
3.1.
Key Points to Remember  
4.
Parameters
5.
Return Value
6.
Examples
6.1.
Example 1: Basic Usage
6.2.
Example 2: Merging Multiple Objects
6.3.
Example 3: Cloning an Object
6.4.
Example 4: Handling Nested Objects
7.
Applications
7.1.
Example: Merging Default Settings
8.
Errors and Exceptions
9.
Supported Browsers
10.
Frequently Asked Questions
10.1.
Can Object.assign() perform deep copies? 
10.2.
What happens if properties in source objects have the same key? 
10.3.
Is Object.assign() mutable? 
11.
Conclusion
Last Updated: Jan 20, 2025
Medium

Object.assign in JavaScript

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The Object.assign method in JavaScript is used to copy the values of all properties from one or more source objects to a target object. This method is commonly used to merge objects or clone an object. It provides a simple and efficient way to work with object properties in JavaScript, making coding easier and more organized.

Object.assign in JavaScript

In this article, you will learn about the syntax of the Object.assign method, how it works, and practical examples of its usage in JavaScript development.

Description  

`Object.assign` is a built-in JavaScript method that copies properties from one or more source objects to a target object. It returns the modified target object. This method is commonly used to merge objects or create a new object by combining properties from multiple objects.  

How Does `Object.assign` Work?  

The syntax for `Object.assign` is :  

Object.assign(target, ...sources)

 

  • target: The object to which properties will be copied. This is the object that will be modified and returned.  
     
  • sources: One or more objects from which properties will be copied.  


Let’s discuss a simple example to understand how `Object.assign` works:  

const target = { a: 1, b: 2 };  
const source = { b: 4, c: 5 };  
const result = Object.assign(target, source);  
console.log(result);
console.log(target); 
You can also try this code with Online Javascript Compiler
Run Code


Output: 

{ a: 1, b: 4, c: 5 }  
{ a: 1, b: 4, c: 5 }  


In this example:  

1. The `target` object initially has properties `a` and `b`.  
 

2. The `source` object has properties `b` and `c`.  
 

3. When `Object.assign` is called, it copies the properties from `source` to `target`.  
 

4. If a property exists in both objects (like `b`), the value from the `source` object overwrites the value in the `target` object.  
 

5. The `result` is the modified `target` object, which now includes properties from both `target` and `source`.  

Key Points to Remember  

- `Object.assign` only copies enumerable & own properties (not inherited ones).  

- It performs a shallow copy, meaning nested objects are copied by reference, not by value.  

- If the `target` object is empty (`{}`), `Object.assign` can be used to create a new object with combined properties. 

Parameters

  1. target: The object to which properties and values will be copied. It is mandatory.
     
  2. sources: One or more source objects whose properties and values will be copied to the target object. This parameter is optional but is usually included.

Return Value

The method returns the modified target object with properties and values merged from the source objects.

Examples

Example 1: Basic Usage

Here is a simple example of how Object.assign() works:

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const result = Object.assign(target, source);
console.log(result);
You can also try this code with Online Javascript Compiler
Run Code


Output:

{ a: 1, b: 4, c: 5 }


Explanation: The value of b in the target object is updated to 4 from the source object, and the property c is added to the target object.

Example 2: Merging Multiple Objects

You can merge multiple objects into the target object:

const target = { a: 1 };
const source1 = { b: 2 };
const source2 = { c: 3 };
const result = Object.assign(target, source1, source2);
console.log(result);
You can also try this code with Online Javascript Compiler
Run Code


Output:

{ a: 1, b: 2, c: 3 }


Explanation: All properties from source1 and source2 are copied to target.

Example 3: Cloning an Object

Object.assign() can also be used to create a shallow copy of an object:

const obj = { x: 10, y: 20 };
const clone = Object.assign({}, obj);
console.log(clone);
You can also try this code with Online Javascript Compiler
Run Code


Output:

{ x: 10, y: 20 }


Explanation: A new object clone is created with the same properties and values as obj.

Example 4: Handling Nested Objects

Keep in mind that Object.assign() performs a shallow copy, not a deep copy:

const obj = { a: 1, b: { c: 2 } };
const shallowCopy = Object.assign({}, obj);
shallowCopy.b.c = 42;
console.log(obj.b.c);
You can also try this code with Online Javascript Compiler
Run Code


Output:

42


Explanation: Changes to the nested object in the copy reflect in the original object because the copy is shallow.

Applications

  1. Merging Objects: Combine properties from multiple objects into one.
     
  2. Cloning Objects: Create shallow copies of objects.
     
  3. Setting Default Values: Merge default configurations with user inputs.

Example: Merging Default Settings

const defaults = { theme: "light", showNotifications: true };
const userSettings = { theme: "dark" };
const settings = Object.assign({}, defaults, userSettings);
console.log(settings);
You can also try this code with Online Javascript Compiler
Run Code


Output:

{ theme: "dark", showNotifications: true }


Explanation: The theme property is overridden by the user setting, while showNotifications retains its default value.

Errors and Exceptions

1. Non-Object Target: If the target is not an object (e.g., null or undefined), a TypeError is thrown:

Object.assign(null, { a: 1 });


Error:

TypeError: Cannot convert null to object

2. Non-Object Sources: Non-object sources are ignored:

const result = Object.assign({}, null, { a: 1 }, "string");
console.log(result);


Output:

{ a: 1 }


Explanation: Only valid objects are copied to the target object.

Supported Browsers

Object.assign() is supported in most modern browsers, including:

  • Google Chrome: Supported from version 45
     
  • Firefox: Supported from version 34
     
  • Safari: Supported from version 9
     
  • Edge: Supported from version 12
     
  • Opera: Supported from version 32
     

For older browsers like Internet Explorer, you can use a polyfill:

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


    sources.forEach(source => {
      if (source) {
        for (let key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
    });
    return target;
  };
}

Frequently Asked Questions

Can Object.assign() perform deep copies? 

No, Object.assign() only performs shallow copies. To deep copy objects, consider using libraries like Lodash or structured cloning.

What happens if properties in source objects have the same key? 

The last source object in the list will override properties with the same key.

Is Object.assign() mutable? 

Yes, it mutates the target object directly. If you need an immutable approach, create a new empty object as the target.

Conclusion

Object.assign() is a versatile method in JavaScript that allows developers to merge objects, clone objects, and set default values with ease. It is supported across modern browsers and can significantly simplify object handling. However, always remember that it performs a shallow copy and does not handle nested objects.

Live masterclass