• Skip to main content
  • Skip to search
  • Skip to select language
  • Get MDN Plus
  • English (US)

Object.assign()

The Object.assign() static method copies all enumerable own properties from one or more source objects to a target object . It returns the modified target object.

The target object — what to apply the sources' properties to, which is returned after it is modified.

The source object(s) — objects containing the properties you want to apply.

Return value

The target object.

Description

Properties in the target object are overwritten by properties in the sources if they have the same key . Later sources' properties overwrite earlier ones.

The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters . Therefore it assigns properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters.

For copying property definitions (including their enumerability) into prototypes, use Object.getOwnPropertyDescriptor() and Object.defineProperty() instead.

Both String and Symbol properties are copied.

In case of an error, for example if a property is non-writable, a TypeError is raised, and the target object is changed if any properties are added before the error is raised.

Note: Object.assign() does not throw on null or undefined sources.

Cloning an object

Warning for deep clone.

For deep cloning , we need to use alternatives, because Object.assign() copies property values.

If the source value is a reference to an object, it only copies the reference value.

Merging objects

Merging objects with same properties.

The properties are overwritten by other objects that have the same properties later in the parameters order.

Copying symbol-typed properties

Properties on the prototype chain and non-enumerable properties cannot be copied, primitives will be wrapped to objects, exceptions will interrupt the ongoing copying task, copying accessors, specifications, browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Related Articles

JavaScript Object.assign() Method

The Object.assign() method is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [[Get]] on the source and [[Set]] on the target. It returns the target object which has properties and values copied from the source object. Object.assign() does not throw on null or undefined source values. 

Parameters:  

Return Value:  Object.assign() returns the target object.

Examples of the above function are provided below.

Example 1:  Here in this example the properties of the object “obj1” i.e. { a: 10 } is copied to the target object “new_obj”.

Output:  

Example 2: Here in this example the properties of three source objects “obj1, obj2, obj3” are copied to the target object “new_obj”. The value of any pre-existing key-value pair that existed in the previous object will be over-written. For example, obj1.b which has a value of 10 will now be overwritten with obj2.b which has a value of 20

Output :  

Example 3: Here in this example the properties of three source objects “obj1, obj2, obj3” are copied to the target object “new_obj” and the target object gets the overwritten values.

Explanation: In the above code the properties are overwritten by other objects that have the same properties later in the same order of parameters.

Applications:  

Errors and Exceptions  

We have a complete list of Javascript Object methods, to check those please go through this JavaScript Object Complete Reference article.

Supported Browsers:

Please Login to comment...

Improve your Coding Skills with Practice

Start your coding journey now.

Home » JavaScript Tutorial » JavaScript Object.assign()

JavaScript Object.assign()

Summary : in this tutorial, you will learn how to use the JavaScript Object.assign() method in ES6.

The following shows the syntax of the Object.assign() method:

The Object.assign() copies all enumerable and own properties from the source objects to the target object. It returns the target object.

The Object.assign() invokes the getters on the source objects and setters on the target. It assigns properties only, not copying or defining new properties.

Using JavaScript Object.assign() to clone an object

The following example uses the Object.assign() method to clone an object .

Note that the Object.assign() only carries a shallow clone, not a deep clone.

Using JavaScript Object.assign() to merge objects

The Object.assign() can merge source objects into a target object which has properties consisting of all the properties of the source objects. For example:

If the source objects have the same property, the property of the later object overwrites the earlier one:

ES6 Object.assign() Sample

Available in Chrome 45+ | View on GitHub | Browse Samples

Object.assign() copies the values (of all enumerable own properties) from one or more source objects to a target object. It has a signature of Object.assign(target, ...sources) . The target object is the first parameter and is also used as the return value. Object.assign() is useful for merging objects or cloning them shallowly.

Live Output

Javascript snippet.

Learn coding interactively.

Popular tutorials, popular examples, reference materials, learn python interactively, javascript object methods.

Related Topics

JavaScript Object getOwnPropertyNames()

JavaScript Object.is()

JavaScript Object.assign()

In this tutorial, you will learn about the JavaScript Object.assign() method with the help of examples.

The Object.assign() method copies all the enumerable properties of the given objects to a single object and returns it.

assign() Syntax

The syntax of the assign() method is:

Here, assign() is a static method. Hence, we need to access the method using the class name, Object .

assign() Parameters

The assign() method takes in:

assign() Return Value

The assign() method returns the target object.

Note: Properties in the target object are overwritten by properties in the sources if they have the same key.

Example 1: Javascript Object.assign() to Clone Objects

In the above example, we have used the assign() method to assign the contents of obj to newObject .

Since assign() modifies the target object and returns the same object, both copy and newObject are clones of one another. As a result, we get identical outputs when we print them both.

Example 2: assign() to Merge Objects

In the above example, we have used assign() to merge the objects o1 , o2 , and o3 into a new object o4 .

Using the empty object {} as a target object ensures that the properties of the other objects are copied to a new object without modifying any of the source objects.

As can be seen from the output, properties of later objects overwrite that of earlier ones. For example,

Note: If the source value is a reference to an object, it only copies the reference value.

Recommended Reading:

Sorry about that.

Related Functions

JavaScript Library

JavaScript Object.keys()

JavaScript Object.values()

Javatpoint Logo

JavaScript Tutorial

Javascript object.

JavaTpoint

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on [email protected] , to get more information about given services.

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] Duration: 1 week to 2 week

RSS Feed

DEV Community

DEV Community

Cover image for JS Fundamentals: Object Assignment vs. Primitive Assignment

Posted on May 8, 2020 • Updated on May 14, 2020

JS Fundamentals: Object Assignment vs. Primitive Assignment

Introduction.

Something I wish I had understood early on in my JavaScript programming career is how object assignment works and how it's different from primitive assignment. This is my attempt to convey the distinction in the most concise way possible!

Learn JS Fundamentals

Looking to learn more JS fundamentals? Consider signing up for my free mailing list !

Primitives vs. Objects

As a review, let's recall the different primitive types and objects in JavaScript.

Primitive types: Boolean, Null, Undefined, Number, BigInt (you probably won't see this much), String, Symbol (you probably won't see this much)

Object types: Object, Array, Date, Many others

How Primitive and Object Assignment Differ

Primitive assignment.

Assigning a primitive value to a variable is fairly staightforward: the value is assigned to the variable. Let's look at an example.

In this case, a is set to the value hello and b is also set to the value hello . This means if we set b to a new value, a will remain unchanged; there is no relationship between a and b .

Object Assignment

Object assignment works differently. Assigning an object to a variable does the following:

Why is this a big deal? Let's explore.

The first line creates the object { name: 'Joe' } in memory and then assigns a reference to that object to variable a . The second line assigns a reference to that same object in memory to b !

So to answer the "why is this a big deal" question, let's mutate a property of the object assigned to b :

That's right! Since a and b are assigned a reference to the same object in memory, mutating a property on b is really just mutating a property on the object in memory that both a and b are pointing to.

To be thorough, we can see this in action with arrays as well.

This Applies to Function Arguments too!

These assignment rules apply when you pass objects to functions too! Check out the following example:

The moral of the story: beware of mutating objects you pass to functions unless this is intended (I don't think there are many instances you'd really want to do this).

Preventing Unintended Mutation

In a lot of cases, this behavior can be desired. Pointing to the same object in memory helps us pass references around and do clever things. However, this is not always the desired behavior, and when you start mutating objects unintentionally you can end up with some very confusing bugs.

There are a few ways to make sure your objects are unique. I'll go over some of them here, but rest assured this list will not be comprehensive.

The Spread Operator (...)

The spread operator is a great way to make a shallow copy of an object or array. Let's use it to copy an object.

A note on "shallow" copying

It's important to understand shallow copying versus deep copying. Shallow copying works well for object that are only one level deep, but nested object become problematic. Let's use the following example:

We successfully copied a one level deep, but the properties at the second level are still referencing the same objects in memory! For this reason, people have invented ways to do "deep" copying, such as using a library like deep-copy or serializing and de-serializing an object.

Using Object.assign

Object.assign can be used to create a new object based on another object. The syntax goes like this:

Beware; this is still a shallow copy!

Serialize and De-serialize

One method that can be used to deep copy an object is to serialize and de-serialize the object. One common way to do this is using JSON.stringify and JSON.parse .

This does have its downsides though. Serializing an de-serializing doesn't preserve complex objects like functions.

A Deep Copy Library

It's fairly common to bring in a deep copy library to do the heavy lifting on this task, especially if your object has an unknown or particularly deep hierarchy. These libraries are typically functions that perform one of the aforementioned shallow copy methods recursively down the object tree.

While this can seem like a complex topic, you'll be just fine if you maintain awareness about how primitive types and objects are assigned differently. Play around with some of these examples and, if you're up for it, attempt writing your own deep copy function!

Top comments (5)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

thisdotmedia_staff profile image

Great article Nick! Well-written, clear, and concise. Really appreciate the images and examples to go along with your main points. This will help a number of devs for sure! Thanks for sharing with us :)

alphavader profile image

Great article, thanks alot!!

caketi profile image

const b = JSON.parse(JSON.serialize(a));

serialize? maybe stringify

rakesh_suryawanshi profile image

fabianaasara profile image

Nice work 🤩easily explained! Thanks.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

Visualizing Promises and Async/Await 🤯

☝️ Check out this all-time classic DEV post

bhartee_sahare profile image

Materialized View on Rails (Postgres)

Bhartee Rameshwar Sahare - Feb 23

bgopikrishna profile image

IndexedDB on steroids using Dexie.js

Gopi Krishna - Feb 27

ryansolid profile image

The Evolution of Signals in JavaScript

Ryan Carniato - Feb 27

sebduta profile image

Complete Guide to useState Hook in React

Sebastian Duta - Feb 27

Once suspended, nas5w will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, nas5w will be able to comment and publish posts again.

Once unpublished, all posts by nas5w will become hidden and only accessible to themselves.

If nas5w is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to Nick Scialli (he/him).

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag nas5w:

nas5w consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy.

Unflagging nas5w will restore default visibility to their posts.

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Related Tags

What is the Object.assign() method in JavaScript?

to assign object

Object.assign() is a method in JavaScript that is used to copy or merge objects.

Object.assign() performs a shallow copy; i.e., it only copies properties, not prototype methods.

Take a look at the function signature below:

svg viewer

Copying an object

Object.assign() returns a target object.

​### Merging objects

In case of a name collision between a source and target property, Object.assign() will overwrite the local property of the target object.

RELATED TAGS

View all Courses

Learn in-demand tech skills in half the time

For Enterprise

For Individuals

For HR & Recruiting

For Bootcamps

Educative Learning

Educative Onboarding

Educative Skill Assessments

Educative Projects

Privacy Policy

Terms of Service

Business Terms of Service

Become an Author

Become an Affiliate

Become a Contributor

Educative Blog

Educative Sessions

Educative Answers

Frequently Asked Questions

GitHub Students Scholarship

Course Catalog

Early Access Courses

Earn Referral Credits

CodingInterview.com

Copyright © 2023 Educative, Inc. All rights reserved.

to assign object

Object.assign

Jakub Włodarczyk

Feb 25, 2018

Object.assign()

Object.assign() is a very useful method for copying values from one object to the other. It accepts two parameters: a target object and a source to copy from. Both of the parameters need to be objects. We can copy from more than one object. Let’s go straight to a simple example:

In case of copying from multiple objects we can separate values with a comma:

The target object doesn’t always need to be an empty object:

If a property exists, it will be overridden:

It’s important to mention that only enumerable properties will be copied. What are these? Well, enumerable is a special flag set on an object. When set to true — a property will be included where we loop through the object. When we create an object it has some flags set by default. We can read their values using Object.getOwnPropertyDescriptors() method:

Let’s confirm that only enumerable properties can be copied:

Setting enumerable flag to false will prevent this property from being copied.

Alternatively, you can use the spread syntax for copying:

Unlike Object.assign() , setters are not triggered.

More from Jakub Włodarczyk

Full Stack Dev (Java + JS)

About Help Terms Privacy

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

Jakub Włodarczyk

Text to speech

IMAGES

  1. Playing with JavaScript Object clone

    to assign object

  2. A Practical Use Case for JavaScript’s Object.assign()

    to assign object

  3. 45 JavaScript ES6

    to assign object

  4. javascript

    to assign object

  5. The Difference Between Object.create and Object.assign

    to assign object

  6. Deep and Shallow Copy with Object.assign JavaScript

    to assign object

VIDEO

  1. Works on any object

  2. How to Assign values to object in R studio

  3. 6.02_Connecting Objects

  4. Object advanced

  5. Issue 6: Objects as Components

  6. Как работает деструктуризация объекта в JS. Метод Object.assign. Урок 21

COMMENTS

  1. What Are Examples of Nonluminous Objects?

    The moon and Earth are examples of non-luminous objects. Non-luminous objects become visible only when they reflect light produced by a luminous object. A luminous object, such as the sun, emits its own light, because it has its own source ...

  2. What Is the Difference Between General and Specific Objectives?

    UNESCO explains that the major difference between general objectives and specific objectives is that a general objective is a statement of the trend of the learning activity that describes the general orientation of a learning curriculum.

  3. What Are Objective Observations?

    Objective observations are observations that involve watching others in an unbiased manner and without attaching stereotypes.

  4. Object.assign()

    The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and

  5. JavaScript Object.assign() Method

    The Object.assign() method is used to copy the values and properties from one or more source objects to a target object.

  6. Using JavaScript Object.assign() Method in ES6

    Object.assign() assigns enumerable and own properties from a source object to a target object. · Object.assign() can be used to clone an object or merge objects.

  7. ES6 Object.assign() Sample

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

  8. JavaScript Object.assign()

    The Object.assign() method copies all the enumerable properties of the given objects to a single object and returns it. Example.

  9. The Object.assign() Method in JavaScript

    The assign() method on the Object constructor in JavaScript is used to merge multiple objects together. You can use it to merge as many

  10. JavaScript Object assign() Method

    The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.

  11. JS Fundamentals: Object Assignment vs. Primitive Assignment

    Creates the object in memory; Assigns a reference to the object in memory to the variable. Why is this a big deal? Let's explore. const

  12. What is the Object.assign() method in JavaScript?

    Object.assign() is a method in JavaScript that is used to copy or merge objects. Object.assign() performs a shallow copy; i.e., it only copies properties

  13. Object.assign

    Object.assign lets us merge one object's properties into another, replacing values of properties with matching names. We can use this to copy an object's values

  14. Object.assign()

    Object.assign() is a very useful method for copying values from one object to the other. It accepts two parameters: a target object and a