Add/Delete JavaScript Object property

How to add or delete property from a JavaScript object ?

Published 2021-07-16

How to add or delete property from a JavaScript object ?

const profile = {
  name: 'Florian',
  age: '30',
  color: 'indigo'
}

// Add a new property

profile.dogName = 'Daryll'
profile['country'] = 'France'

console.log(profile)
/* 
{
  name: 'Florian',
  age: '30',
  color: 'indigo',
  dogName: 'Daryll',
  country: 'France'
} 
*/

// With the delete operator, you can remove any existing property from an object

delete profile.age

// The delete operator return true when a property is deleted

console.log(delete profile.color ? 'Color successuflly deleted' : 'Something went wrong') // 'Color successuflly deleted'

console.log(profile)
// { name: 'Florian', dogName: 'Daryll', country: 'France' }

Related Tutorials :