How to create new property in object javascript

In JavaScript, you can create a new property in an object using the dot notation or the bracket notation.

Dot Notation:

myObject.newProperty = 'value';

This creates a new property called newProperty with the value 'value' on the myObject object.

Bracket Notation:

myObject['newProperty'] = 'value';

This also creates a new property called newProperty with the value 'value' on the myObject object.

Using the Object.defineProperty() method:

Object.defineProperty(myObject, 'newProperty', {
  value: 'value',
  writable: true,
  configurable: true
});

This method allows you to define a property with additional attributes, such as writable (whether the property can be changed) and configurable (whether the property can be deleted).

Using the Object.assign() method:

const myObject = {};
Object.assign(myObject, { newProperty: 'value' });

This method creates a new property called newProperty with the value 'value' on the myObject object.

Using the ES6 syntax:

const myObject = {...{ newProperty: 'value' } };

This syntax creates a new property called newProperty with the value 'value' on the myObject object.

Note that in all cases, if the property already exists, its value will be updated. If you want to add a new property only if it doesn't already exist, you can use the in operator to check if the property exists before creating it:

if (!('newProperty' in myObject)) {
  myObject.newProperty = 'value';
}