Object. assign()
Copies properties from one or more objects into a target object.
- Returns
- The target object.
- Changes the original
- Yes
Example
#const defaults = { theme: 'dark', sound: true }
const saved = { sound: false }
const settings = Object.assign({}, defaults, saved)
console.log(settings)
console.log({ ...defaults, ...saved })Definition and usage
#The Object.assign(target, ...sources) method copies own, enumerable properties from the source objects into the target object, and returns that object. For repeated keys, later sources overwrite earlier ones.
Note that the target object gets modified. To create a new object instead, pass an empty object as the target: Object.assign({}, a, b). In modern code, the { ...a, ...b } syntax does the same thing.
The copy is shallow. Nested objects aren’t cloned, only shared. For a deep copy, use structuredClone().
Syntax
#Object.assign(target, source1, source2, …)Parameters
#target
object
The object the properties will be copied into. It will be modified.source1…sourceN
objects
The objects the properties are copied from.
More examples
#const original = { name: 'Emma', stats: { level: 3 } }
const copy = Object.assign({}, original)
copy.stats.level = 10
console.log(original.stats.level)Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- To merge objects, the
{ ...a, ...b }syntax is used more often these days, since it doesn’t mutate either one. - For a copy that includes nested objects, use
structuredClone().
Related entries
#- Spread (...)The spread syntax spreads an array, string, or object out into individual elements: for copying, merging, and passing arguments.
- structuredClone()Creates a deep copy of a value, including nested objects, dates, Maps, and Sets.
- Object.freeze()Freezes an object, blocking the addition, removal, and change of its properties.
- Object.entries()Returns an array of an object’s [key, value] pairs.
Spotted a mistake or missing an example? Write to us.