Trusted answers to developer questions

How to Add Property to an object in JavaScript

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

There’re a few ways to add properties to an object in JavaScript. One way is to add a property using the dot notation:

obj.foo = 1;

We added the foo property to the obj object above with value 1.

We can also add a property by using the bracket notation:

obj['foo'] = 1;

It does the same thing as the first example, but we can have invalid property identifiers in the string.

So, we can write something like:

obj['foo-bar'] = 1;
var obj = { Name: "Joe" };
obj.Age = 12;
console.log(obj.Age)
obj['Country'] = "USA"
console.log(obj.Country)

Remember: 'foo-bar' isn’t a valid identifier, but we can add it as a property.

Object.defineProperty

We can also use the Object.defineProperty function:

Object.defineProperty(obj, 'foo', {
  value: 1
})

We can have more control over how the property will act with this method. In addition to setting the value with the value property, we can also set it to be writable with the writable property, and enumerable with the enumerable property.

Enumerable means that it’ll be retrieved or looped through with Object.keys or the for-in loop.

Writable determines if we can set a new value for the property.

RELATED TAGS

javascript
property
defineproperty

CONTRIBUTOR

John Au-Yeung
Attributions:
  1. undefined by undefined
Did you find this helpful?