Updating Properties

JavaScript objects are highly dynamic. You are not locked into the properties you defined when the object was originally created.

You can update existing keys—or add entirely new ones—using the dot (.) operator. If the property already exists, its value is overwritten. If it doesn’t exist, it is created on the fly.

Modifying Objects

const apple = {
  name: "Apple",
  radius: 2,
  color: "red",
};

// Add a brand new property
apple.numSeeds = 3; 

// Update an existing property
apple.color = "green"; 

console.log(apple);
// Output: { name: 'Apple', radius: 2, color: 'green', numSeeds: 3 }

Practical Example

Often, you will receive an object as a function parameter, attach new data to it, and return the modified object.

function addID(campaignRecord) {
  // We attach a new 'id' property by combining two existing ones
  campaignRecord.id = campaignRecord.campaignName + "-" + campaignRecord.senderName;
  
  return campaignRecord;
}

const record = {
  campaignName: "summerSales",
  senderName: "adam"
};

const updatedRecord = addID(record);
console.log(updatedRecord.id); 
// Output: "summerSales-adam"