Object.assign And Spread Merge Shallow

Object.assign and spread merge one level deep: overridden keys point to new objects while untouched nested objects stay shared with the source.

JavascriptConfig Management

Code

javascriptsnippet
22 lines
// Object.assign 和展开运算符都是浅合并:同名键顶层覆盖,嵌套对象只搬引用
const config = {
  timeout: 30,
  cache: { ttl: 60 },
};

const patch = { timeout: 60, cache: { ttl: 300 } };

const viaAssign = Object.assign({}, config, patch);
const viaSpread = { ...config, ...patch };

console.log('assign:', viaAssign.timeout, viaAssign.cache.ttl);
console.log('spread:', viaSpread.timeout, viaSpread.cache.ttl);

// 被覆盖的 cache 是新对象:源对象不受影响
console.log('source untouched:', config.cache.ttl);
console.log('distinct nested object:', viaSpread.cache !== config.cache);

// 未被覆盖的嵌套键则共享引用:改副本会穿透到源
const partial = { ...config };
partial.cache.ttl = 120;
console.log('alias write reached source:', config.cache.ttl);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

assign: 60 300
spread: 60 300
source untouched: 60
distinct nested object: true
alias write reached source: 120

What the code does

Top-level bindings config, patch, viaAssign, viaSpread hold the demo state — nothing sits inside a function scope.

Using it

The run emits 5 labeled sections — assign:, spread:, source untouched:, distinct nested object:, alias write reached source: — one per step.

Key statements

const patch = { timeout: 60, cache: { ttl: 300 } };
const viaAssign = Object.assign({}, config, patch);
const viaSpread = { ...config, ...patch };

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. Its state lives in module-level bindings: `config`, `patch`, `viaAssign`.