JS Built-ins
ObjectObject.assignbeginner

Object.assign() β€” shallow clone

πŸ“– Usage Example
// Merge source into target
const target = { a: 1 }
Object.assign(target, { b: 2 })   // β†’ { a: 1, b: 2 }

Use Object.assign() to copy properties from one or more source objects into a target object.

Object.assign() for shallow cloning

Passing an empty object {} as the target with one source is a common way to create a shallow clone of an object.

Challenge: Implement shallowClone(obj) that returns a shallow copy of obj using Object.assign.

const orig = { a: 1, b: 2 }
const copy = shallowClone(orig)
copy === orig // β†’ false
copy          // β†’ { a: 1, b: 2 }
πŸ’‘ Hints (2)
  • β€’ Use `Object.assign({}, obj)` to copy into a fresh empty object.
  • β€’ "Shallow" means nested objects are still shared by reference.