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.