Science Knowings: JavaScript Course For Social Media

Object.assign() Method

Same as Object.freeze() but

Object.seal() makes an object immutable, it still allows to modify its properties' but with Object.assign() we can copy the properties of a sealed object to another object, but we cannot add new properties.

Object.assign() Method

The Object.assign() method is used to copy the properties from one or more source objects to a target object. It's a powerful tool for combining and manipulating objects in JavaScript.

Syntax and Usage

Object.assign(target, ...sources)

where:
target The target object that will receive the properties.
sources One or more source objects from which properties will be copied.

Copying Properties

Object.assign() copies the enumerable properties from the source objects to the target object. The order of the source objects matters, as properties from later sources overwrite properties from earlier sources.

Updating Existing Properties

If a property in the target object already exists, its value is overwritten by the value from the source object.

Merging Objects

Object.assign() can be used to merge multiple objects into a single target object, combining their properties.

Combining Multiple Objects

const mergedObject = Object.assign({}, object1, object2, object3);

Example Usage

const obj1 = { name: 'Alice', age: 30 };
const obj2 = { job: 'Developer', city: 'New York' };

const mergedObj = Object.assign({}, obj1, obj2);

console.log(mergedObj); // { name: 'Alice', age: 30, job: 'Developer', city: 'New York' }

Spread Operator vs. Object.assign()

The spread operator (...) can also be used to copy object properties, but Object.assign() provides more control over the merging process and allows for deep copying.

Deep Copy vs. Shallow Copy

Object.assign() performs a shallow copy by default, copying the values of properties, but not the properties of nested objects. For a deep copy, consider using a library or implementing your own deep copy function.

Use Cases

  • Copying and Combining Objects
  • Creating a New Object with Specific Properties
  • Updating Existing Objects Dynamically
  • Merging Data from Multiple Sources
  • Browser Support

    Object.assign() is supported in most modern browsers, including Chrome, Firefox, Safari, and Edge.

    Polyfill for Older Browsers

    For older browsers that don't support Object.assign(), a polyfill can be used to implement the functionality.

    Conclusion

    Object.assign() is a versatile method for copying and merging objects in JavaScript. It's widely used for various tasks, ranging from creating new objects to updating existing ones. By understanding its usage and limitations, you can effectively utilize it to manage and manipulate objects in your code.