JavaScript

Copy an object with spread syntax

Object spread creates a new object from another object’s enumerable own properties. It is useful for changing a few top-level fields while retaining the remaining values.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const original = {theme: "light", options: {size: 12}};
const updated = {...original, theme: "dark"};
console.log(original.theme, updated.theme);
console.log(original.options === updated.options);

How it works

Properties written later override earlier properties with the same key. Placing theme after the spread changes the copy while leaving the original top-level theme alone. Both objects still point to the same nested options object.

Limits and mistakes

Spread is a shallow copy and does not preserve a custom prototype or non-enumerable properties. Updating nested objects requires copying each affected level or using a suitable deep-clone strategy. A copy is not automatically an immutable value.

Check the result

Expect light dark, followed by true. Modify updated.options.size in a disposable example and observe the shared nested reference before relying on isolation.

Sources

Reference documentation for the behavior used in this guide: