What is the difference between Object.assign and the spread operator for objects?
Answer
Both merge objects but have nuances. Object.assign(target, source1, source2) copies own enumerable properties from sources to target, modifying and returning target. Mutates the first argument. Use {} as first arg to avoid mutation: const merged = Object.assign({}, obj1, obj2). Spread operator {...obj1, ...obj2} creates a new object without mutating anything — cleaner and more readable. Both perform shallow copies — nested objects are still references. Both copy only own enumerable properties — Symbol-keyed properties are copied by spread but not by Object.assign with certain patterns. Key difference: Object.assign triggers setters on the target; spread does not. Object.assign also works for patching existing objects directly: Object.assign(this.state, updates). For deep cloning, use structuredClone(obj) (modern), JSON.parse(JSON.stringify(obj)) (serializable data only), or a library like Lodash _.cloneDeep().