Copying and Merging Objects in JavaScript: Object.assign, Spread, Defaults and Deep Merge
How Object.assign and object spread copy properties, which wins on collisions, defaults and overrides, filling only missing keys, getters and setters, nested objects and deep merge, prototype pollution, immutable updates and the cost of spreading in loops.
kvi5hnuCode Sprout team member7 min readOn this page
Copying properties from one object into another is one of the most frequent operations in JavaScript: applying user settings on top of defaults, building an updated version of some state, combining options passed to a function. The language has two tools for it, Object.assign (ES2015) and object spread { ...obj } (ES2018). They look interchangeable, and usually are, but not always.
Article 21 explained shallow vs deep copies and structuredClone. This article focuses on merging: combining several objects into one.
Object.assign
Object.assign(target, ...sources) copies the own, enumerable properties (string and symbol keys) of each source into target, in order, and returns target:
const target = { a: 1 };
const result = Object.assign(target, { b: 2 }, null, { a: 3 });
console.log(result === target, target);
true { a: 3, b: 2 }
- Sources are processed left to right, so later sources win when keys collide.
nullandundefinedsources are skipped.- The target is modified. To leave everything unchanged, pass a new empty object as the target:
Object.assign({}, a, b).
Object spread
Inside an object literal, ...expression copies the own enumerable properties of the expression's value into the new object, at that position:
const position = { x: 10, y: 20 };
const size = { width: 300, height: 150 };
const box = { ...position, ...size, label: "card" };
console.log(box);
console.log({ id: 1, ...{ id: 2 } }.id, { ...{ id: 2 }, id: 1 }.id); // position decides
{ x: 10, y: 20, width: 300, height: 150, label: 'card' }
2 1
The rule is the same, last one wins, but with spread you see the order directly in the literal: properties written after a spread override it, properties written before it are overridden by it. Spread always creates a new object, so it never modifies its sources.
Spreading null, undefined or a number does nothing; spreading a string or array copies its indexes as keys ({ ..."hi" } is { '0': 'h', '1': 'i' }).
Spread also makes conditional properties easy, since spreading false adds nothing:
const includeDebug = true;
const options = { retries: 3, ...(includeDebug && { debug: true }), ...(false && { never: 1 }) };
console.log(options);
{ retries: 3, debug: true }
Defaults and overrides
The classic use: start from defaults and apply whatever the caller provided:
const defaults = { theme: "light", fontSize: 14, beta: false };
const userSettings = { fontSize: 18 };
const settings = { ...defaults, ...userSettings };
console.log(settings);
// The wrong way round: defaults overwrite the user's choices.
const broken = Object.assign({ fontSize: 18 }, defaults);
console.log(broken.fontSize);
{ theme: 'light', fontSize: 18, beta: false }
14
Order is everything: defaults first, overrides last.
The undefined trap
A key that's present with the value undefined still overrides:
const defaults = { fontSize: 14 };
const fromForm = { fontSize: undefined }; // field left empty
console.log({ ...defaults, ...fromForm }.fontSize);
const withoutUndefined = (obj) =>
Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
console.log({ ...defaults, ...withoutUndefined(fromForm) }.fontSize);
undefined
14
This is different from default parameters and destructuring defaults (article 28), which do treat undefined as missing. Filter out undefined values first, or apply per-property defaults with ??.
Filling in only what's missing
To add properties from sources without overwriting existing ones, write a small helper:
function fillMissing(target, ...sources) {
for (const source of sources) {
for (const [key, value] of Object.entries(source)) {
if (!Object.hasOwn(target, key)) target[key] = value;
}
}
return target;
}
const saved = { volume: 7 };
console.log(Object.assign({ ...saved }, { volume: 5, muted: false }, { muted: true, speed: 1 }));
console.log(fillMissing({ ...saved }, { volume: 5, muted: false }, { muted: true, speed: 1 }));
{ volume: 5, muted: true, speed: 1 }
{ volume: 7, muted: false, speed: 1 }
With Object.assign, the last value wins; with fillMissing, the first one does.
What gets copied, exactly
Both tools copy only own enumerable properties. Inherited properties, non-enumerable properties and the prototype are left behind:
const item = Object.create({ inherited: 1 });
item.own = 2;
console.log({ ...item }, Object.assign({}, item));
{ own: 2 } { own: 2 }
So copying a class instance with spread gives a plain object without its methods. And a copy of a frozen object isn't frozen: the copy is a brand-new ordinary object.
Getters and setters: assign vs spread
The one real difference between the two tools:
- Both read source properties normally, so a source getter is called and its current value is copied as a plain data property. The getter itself isn't copied.
Object.assignwrites with ordinary assignment, so a setter on the target runs. Spread defines brand-new properties on a new object, so no setter is ever involved.
const source = { get stamp() { return "computed"; } };
const copy = { ...source };
console.log(Object.getOwnPropertyDescriptor(copy, "stamp").value, typeof Object.getOwnPropertyDescriptor(copy, "stamp").get);
const logged = { set name(v) { console.log("setter received", v); } };
Object.assign(logged, { name: "Ana" });
computed undefined
setter received Ana
To copy getters and setters as accessors, copy the property descriptors: Object.defineProperties({}, Object.getOwnPropertyDescriptors(source)) (part 14).
Nested objects: shallow vs deep merge
Spread and Object.assign work at the top level only. A nested object in a later source replaces the whole nested object from an earlier one; it isn't merged into it:

const defaults = { theme: "light", db: { host: "localhost", port: 5432 } };
const overrides = { db: { port: 6000 } };
console.log({ ...defaults, ...overrides });
{ theme: 'light', db: { port: 6000 } }
The host setting is gone. For nested configuration you need a deep merge, which recurses into nested plain objects:
const isPlainObject = (v) =>
v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
function deepMerge(base, extra) {
const out = { ...base };
for (const [key, value] of Object.entries(extra)) {
if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
out[key] = isPlainObject(value) && isPlainObject(base[key])
? deepMerge(base[key], value)
: value;
}
return out;
}
const defaults = { theme: "light", db: { host: "localhost", port: 5432 } };
const merged = deepMerge(defaults, { db: { port: 6000 } });
console.log(merged, defaults.db.port);
console.log(deepMerge({ tags: ["a", "b"] }, { tags: ["c"] })); // arrays are replaced
{ theme: 'light', db: { host: 'localhost', port: 6000 } } 5432
{ tags: [ 'c' ] }
Decisions every deep merge has to make: arrays replace or concatenate? What about dates, maps or class instances? Libraries (Lodash's merge, deepmerge) make different choices, so read their documentation. This one replaces arrays and anything that isn't a plain object.
Prototype pollution: why the key check is there
JSON.parse('{"__proto__": {...}}') produces an object with an own key named "__proto__". A naive recursive merge that does target[key] = ... with that key walks into target.__proto__, which for a plain object is Object.prototype, and writes properties onto it. Every object in the program then inherits them:
function naiveMerge(target, source) {
for (const key in source) {
if (typeof source[key] === "object" && source[key] !== null) {
target[key] ??= {};
naiveMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
}
return target;
}
const untrusted = JSON.parse('{"__proto__": {"isAdmin": true}}');
naiveMerge({}, untrusted);
console.log({}.isAdmin); // every object now "has" isAdmin
delete Object.prototype.isAdmin; // clean up
console.log({}.isAdmin);
true
undefined
This vulnerability class, prototype pollution, has affected many popular libraries and can lead to authorization bypasses when code checks flags like user.isAdmin. Defenses: skip __proto__, constructor and prototype keys when merging untrusted data (as deepMerge above does), merge into Object.create(null) objects or Maps, validate input against a schema, and keep merge libraries up to date. Node.js also has a --disable-proto flag that removes the __proto__ accessor.
Immutable updates
Front-end frameworks such as React and Redux expect state to be updated by creating new objects rather than mutated, so they can detect changes by reference. Spread is the standard tool: copy each level along the path you change:
const state = { user: { name: "Ana", prefs: { theme: "light" } }, count: 1 };
const next = {
...state,
user: { ...state.user, prefs: { ...state.user.prefs, theme: "dark" } },
};
console.log(next.user.prefs.theme, state.user.prefs.theme);
console.log(next.count === state.count, next.user === state.user);
dark light
true false
Unchanged parts are shared, changed parts are new. For deeply nested updates, libraries like Immer let you write mutating-style code that produces new objects for you.
Performance: spreading in a loop
Spread copies every property each time. Building an object by spreading the accumulator inside reduce copies a growing object on every step, which is O(n²):
// Quadratic: each step copies everything collected so far
const slow = pairs.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});
// Linear alternatives
const fast = Object.fromEntries(pairs);
const alsoFast = {};
for (const [k, v] of pairs) alsoFast[k] = v;
With a few dozen keys it doesn't matter; with tens of thousands it's the difference between milliseconds and seconds.
Common questions
Object.assign or spread?
Use spread to create a new object; it's shorter and doesn't trigger setters. Use Object.assign when you deliberately want to modify an existing object, such as filling in properties of this in a constructor: Object.assign(this, options).
Is { ...obj } a deep copy?
No, it's shallow: nested objects and arrays are shared between the copy and the original. Use structuredClone(obj) for a deep copy of plain data (article 21).
Does spread copy symbol keys?
Yes, own enumerable symbol-keyed properties are copied by both spread and Object.assign. JSON.stringify is the one that skips them.
What happens with duplicate keys in a literal, like { a: 1, ...x, a: 3 }?
They're allowed, and the last one wins, so a is 3 regardless of x. Linters flag duplicate literal keys (ESLint's no-dupe-keys), because they're usually a mistake.
Summary
Object.assign(target, ...sources)copies own enumerable properties intotarget, modifies it and returns it;{ ...a, ...b }creates a new object.- Later sources win; write defaults first and overrides last.
- An explicit
undefinedvalue overrides a default; filter it out if it means "not set". - Neither tool copies inherited or non-enumerable properties; getters are called and their values copied;
Object.assigntriggers setters on the target, spread doesn't. - Both are shallow: nested objects are replaced, not merged. Use a deep merge for nested configuration, and skip
__proto__,constructorandprototypekeys to avoid prototype pollution. - Use spread at each level for immutable updates; avoid spreading an accumulator inside a loop.
Practice Questions
What does this print?
const a = { x: 1, y: { z: 1 } };
const b = { ...a };
b.x = 2;
b.y.z = 2;
console.log(a.x, a.y.z);
Answer
1 2. The copy is shallow: x is independent, but y refers to the same nested object in both.
What does this print?
console.log(Object.assign({}, { a: 1 }, { a: undefined }, { b: 2 }));
Answer
{ a: undefined, b: 2 }. The second source's explicit undefined overwrites a; undefined values are copied like any other.
Write withDefaults(options) that applies these defaults and lets the caller override either one:
{ retries: 3, timeout: 1000 }
Answer
const withDefaults = (options = {}) => ({ retries: 3, timeout: 1000, ...options });
Defaults come first, so anything in options wins.
Given this code, create a new state with 4 added to items and total updated, without mutating state.
const state = { items: [1, 2], total: 3 }
Answer
const next = { ...state, items: [...state.items, 4], total: state.total + 4 };
The array is copied with spread too; state.items.push(4) would mutate the original.
Next: JSON in JavaScript: JSON.stringify and JSON.parse, Replacers, Revivers and Pitfalls

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.