How to use JavaScript to add a new key/value pair to an existing object? Given an object like:

var obj = {key1: value1, key2: value2};

How can I add key3 with value3 to it? What’s the correct way to perform a JavaScript add to object operation?

Honestly, when I’m just working with objects and the keys are known ahead of time, I stick with dot notation — it’s the simplest and cleanest.

var obj = { key1: 'value1', key2: 'value2' };
obj.key3 = 'value3';
console.log(obj);
// { key1: 'value1', key2: 'value2', key3: 'value3' }

This is usually my go-to when I know exactly what property I need. If you’re starting out, this is the most straightforward way for any javascript add to object task. Clean, readable, and just gets the job done.

Yeah, dot notation is great — until you don’t know the key name upfront. Happens a lot when working with user input or iterating over dynamic fields. That’s where bracket notation comes in handy:

var obj = { key1: 'value1', key2: 'value2' };
var newKey = 'key3';
obj[newKey] = 'value3';
console.log(obj);
// { key1: 'value1', key2: 'value2', key3: 'value3' }

This method is a lifesaver when you’re dealing with dynamic keys. It makes your javascript add to object logic adaptable and scalable — especially in loops or APIs.

Exactly! And building on that — if you want to keep the original object untouched and return a new one (which is often the case in React or functional-style coding), the spread operator is pure gold:

var obj = { key1: 'value1', key2: 'value2' };
var newObj = { ...obj, key3: 'value3' };
console.log(newObj);
// { key1: 'value1', key2: 'value2', key3: 'value3' }

This way, the original obj remains unchanged. It’s super useful when you’re handling immutable state. So yeah — another solid approach for javascript add to object without mutation.