JavaScript Object-add, update and delete properties

JavaScript Object-add, update and delete properties

JavaScript object is a collection of properties, and property is a combination of a name (or key) and a value. Object manipulation is very easy but as we are human beings we are always prone to forget. So here are some of the ways to add, update and delete properties from an object.

Adding a property to an object:

We can add the property to an object by simply giving it a value. Example: we are adding the property husband and giving the value directly.

var manchesterUnited= {
  name: 'Lisandro Martinez',
  postion: 'Defender',
}
manchesterUnited.jerseyNumber= '6'// the jerseyNumber property has been added
console.log(manchesterUnited)

Console output

1.png

Deleting property from an object:

We can delete any property from an object by using the keyword delete. The keyword deletes both the value of the property and the property itself. After deleting, the property can't be used until it's updated again.

var manchesterUnited= {
  name: 'Paul Pogba',
  postion: 'Midfielder',
  jerseyNumber: '6',
}
delete manchesterUnited.jerseyNumber;// here the jerseyNumber has been deleted
console.log(manchesterUnited)

Console Output

1.png

Updating the property of an object:

Updating the property of an object literally means updating the value of an object, we can do that simply just by reassigning the value to the same key.

var manchesterUnited= {
  name: 'Bruno Fernandes',
  postion: 'Midfielder',
  jerseyNumber: '18',
 }
manchesterUnited.jerseyNumber= '8'
console.table(manchesterUnited)

Console output

1.png

Apart from this, there is more way to add, delete or update the property of an object. We will discuss it in my next blog but for now (especially for the beginner) by understanding only this technique, you will be able to play with JavaScript objects.

Have fun, and happy coding ✌️