In JavaScript, you can add a new property to an existing object dynamically. This can be useful when you need to store additional information for an object at runtime. To add a property to an object, you can simply use the dot notation or square brackets. Here's how you can do it:
Using the dot notation:
let obj = {key1: 'value1'};
obj.key2 = 'value2';
console.log(obj); // Output: {key1: 'value1', key2: 'value2'}
Using square brackets:
let obj = {key1: 'value1'};
obj['key2'] = 'value2';
console.log(obj); // Output: {key1: 'value1', key2: 'value2'}
It's important to note that when using square brackets to add a new property, the property name can be a variable. This allows for dynamic property assignment based on runtime conditions.
const propertyName = 'key3';
obj[propertyName] = 'value3';
console.log(obj); // Output: {key1: 'value1', key2: 'value2', key3: 'value3'}
By following these simple methods, you can easily add properties to an object in JavaScript, making your code more flexible and dynamic.