Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Object.assign: copy own values

Object.assign copies enumerable own property values from sources into one target object.

Version: ECMAScript 2015 onward; example target: Node.js 24.22.2

Syntax

Object.assign(target, ...sources)

Object.assign(target, ...sources) first applies ToObject to target, so null and undefined throw TypeError, while a primitive target is boxed and returned as an object. Sources are processed left to right; null and undefined are skipped, and other primitives are boxed. A later source can overwrite an earlier value.

For each source, the algorithm takes an OwnPropertyKeys snapshot. For every key it then checks the current own descriptor and, if enumerable, performs Get on the source and Set on the target with throwing enabled. It therefore copies enumerable own string and symbol keys, but not inherited or non-enumerable properties. Getters, setters, and Proxy traps can run or throw.

This is a shallow value copy: descriptors, the prototype, and nested objects are not cloned. The operation is not transactional—if writing to a read-only or non-extensible target, or user code, throws, earlier writes remain. The method has existed since ECMAScript 2015. For untrusted sources, select allowed keys instead of treating assign as a safe merge.

Examples

const token = Symbol("token");
const nested = { enabled: true };
const source = { get score() { console.log("get score"); return 7; }, nested };
Object.defineProperty(source, "hidden", { value: 9, enumerable: false });
source[token] = "ok";
const target = { score: 1, label: "base" };
const result = Object.assign(target, { label: "first" }, source);
console.log(result === target, result.label, result.score, result[token], Object.hasOwn(result, "hidden"));
console.log(result.nested === nested);
const partial = {};
const failing = {};
Object.defineProperties(failing, {
  b: { enumerable: true, get() { throw new Error("stop"); } },
  c: { enumerable: true, value: 3 }
});
try { Object.assign(partial, { a: 1 }, failing); } catch (error) {
  console.log(error.message, Object.hasOwn(partial, "a"), Object.hasOwn(partial, "c"));
}

Result

get score
true first 7 ok false
true
stop true false

The example shows source order, a getter, a Symbol, omission of a non-enumerable property, a shared reference, and a partial write after failure.

Sources