What happens when Object.assign() encounters a non-writable property?

Object.assign() throws a TypeError when encountering a non-writable property.

If Object.assign() tries to copy a property to a target object where the property is non-writable, it will throw a TypeError. This happens because the method attempts to set a value on a property that cannot be changed. The copying process is interrupted, and any properties that were successfully copied before the error will remain on the target object.

const target = Object.defineProperty({}, 'foo', {
  value: 1,
  writable: false
});
try {
  Object.assign(target, { foo: 2 });
} catch (e) {
  console.log(e); // TypeError: Cannot assign to read only property 'foo'
}
More cards4
Show all