How do you add new properties dynamically to an existing JavaScript object? | A1Lab@FahadM to JavaScriptEnglish • 4 days ago

How do you add new properties dynamically to an existing JavaScript object?

message-square
0

To add new properties dynamically to a JavaScript object without mutating the original object in shared or state code, use computed property syntax with object spread ({ ...targetObj, [key]: value })—and guard against prototype pollution by rejecting dangerous keys like "__proto__", "constructor", and "prototype". When you intentionally need to assign a dynamic property onto a local/mutable object in place, use bracket notation (obj[key] = value) or Object.defineProperty(obj, key, descriptor) after validating key and obj.


1. Non-Mutating Dynamic Property Addition with Spread and Computed Keys

Validate that sourceObj is a plain/non-null object and key is a safe property name, then return a brand-new object containing existing properties plus [key]: value without mutating sourceObj:

// Return a new object with a dynamic property added without mutating sourceObj
function withDynamicProperty(sourceObj, key, value) {
  if (typeof sourceObj !== "object" || sourceObj === null || Array.isArray(sourceObj)) {
    throw new TypeError("Expected sourceObj to be a non-null plain/record object.");
  }

  if (typeof key !== "string" && typeof key !== "symbol") {
    throw new TypeError("Property key must be a string or symbol.");
  }

  if (typeof key === "string") {
    const normalizedKey = key.trim();
    if (
      normalizedKey === "" ||
      normalizedKey === "__proto__" ||
      normalizedKey === "constructor" ||
      normalizedKey === "prototype"
    ) {
      throw new RangeError(`Unsafe or invalid property key: "${String(key)}"`);
    }

    return {
      ...sourceObj,
      [normalizedKey]: value
    };
  }

  return {
    ...sourceObj,
    [key]: value
  };
}

// Example usage:
const baseUser = Object.freeze({ id: 42, role: "member" });
const updatedUser = withDynamicProperty(baseUser, "lastLoginAt", "2026-11-28T11:42:00+05:00");
console.log(updatedUser); // { id: 42, role: "member", lastLoginAt: "2026-11-28T11:42:00+05:00" }
console.log(baseUser); // { id: 42, role: "member" }
  • Non-mutating & Object.freeze() friendly: Works safely even when sourceObj is frozen or shared across callers.
  • Prototype-key guard: Blocks "__proto__", "constructor", and "prototype" from being written as dynamic keys.

2. Assigning Dynamic Properties in Place (Bracket Notation & Object.defineProperty)

When updating a local mutable object in place—or when you need explicit control over enumerable, writable, or configurable descriptors—use bracket notation (target[key] = value) or Object.defineProperty(target, key, ...) with explicit guards:

// Set a dynamic property in place on a mutable object with key and descriptor safety
function setDynamicPropertyInPlace(target, key, value, { enumerable = true, writable = true, configurable = true } = {}) {
  if (typeof target !== "object" || target === null || Array.isArray(target)) {
    throw new TypeError("Expected target to be a non-null object.");
  }

  if (Object.isFrozen(target)) {
    throw new TypeError("Cannot add properties to a frozen object.");
  }

  if (typeof key !== "string" && typeof key !== "symbol") {
    throw new TypeError("Property key must be a string or symbol.");
  }

  if (typeof key === "string" && (key === "__proto__" || key === "constructor" || key === "prototype")) {
    throw new RangeError(`Refusing unsafe key "${key}".`);
  }

  Object.defineProperty(target, key, {
    value,
    enumerable: Boolean(enumerable),
    writable: Boolean(writable),
    configurable: Boolean(configurable)
  });

  return target;
}

// Example usage:
const metrics = { views: 10 };
setDynamicPropertyInPlace(metrics, "clicks", 3);
console.log(metrics); // { views: 10, clicks: 3 }
  • Bracket notation for variable keys: obj[dynamicKey] evaluates dynamicKey as an expression, unlike obj.dynamicKey which looks for a literal property named "dynamicKey".
  • Descriptor control: Object.defineProperty() lets you attach non-enumerable metadata or read-only properties when needed.

3. Common Traps to Avoid

Adding properties dynamically to a JavaScript object often runs into a few pitfalls:

  • Using dot notation (obj.key = val) with a variable name: obj.key creates a literal property named "key" instead of reading the string stored inside key.
  • Allowing untrusted keys like "__proto__" or "constructor": Assigning dynamic keys from external input without filtering can trigger prototype pollution or overwrite inherited constructors.
  • Mutating frozen or shared state objects in place: Calling obj[key] = val on an Object.freeze() object throws a TypeError in strict mode and can cause subtle state bugs on shared references—prefer { ...obj, [key]: val } or a Map for arbitrary dynamic keys.

TL;DR: Use { ...obj, [key]: value } (with unsafe-key checks) to add a dynamic property without mutating obj, or obj[key] = value / Object.defineProperty() on a mutable object—and consider new Map() when keys are arbitrary or frequently added/deleted.