add a property to an object in javascript

To add a property to an object in JavaScript, you can use dot notation or bracket notation. Here's an example using dot notation:

index.tsx
// Define an object
const obj = {
  name: 'John',
  age: 30
};

// Add a new property using dot notation
obj.city = 'New York';

console.log(obj); // { name: 'John', age: 30, city: 'New York' }
194 chars
11 lines

In this example, we define an object obj with two properties: name and age. To add a new property called city, we simply use dot notation and assign a value to it ('New York' in this case).

Alternatively, you can use bracket notation to add a new property to an object:

index.tsx
// Define an object
const obj = {
  name: 'John',
  age: 30
};

// Add a new property using bracket notation
obj['city'] = 'New York';

console.log(obj); // { name: 'John', age: 30, city: 'New York' }
201 chars
11 lines

In this example, we use bracket notation and the property name is enclosed in quotes. The effect is the same as when using dot notation.

gistlibby LogSnag