How do I remove a property from a JavaScript object?

How do I remove a property from a JavaScript object?
How do I remove a property from a JavaScript object?

To remove a property from a JavaScript object, you can use the delete operator. The delete operator removes a property from an object.

Here’s an example of how to use the delete operator to remove a property from an object:

const obj = {
  name: 'John',
  age: 30,
  city: 'New York'
};

delete obj.age;
console.log(obj); // { name: 'John', city: 'New York' }

Keep in mind that the delete operator only removes the property from the object. If the property has a value of undefined, the delete operator will not affect it.

const obj = {
  name: 'John',
  age: undefined
};

delete obj.age;
console.log(obj); // { name: 'John', age: undefined }

To remove a property and set its value to undefined, you can use the undefined keyword.

const obj = {
  name: 'John',
  age: 30
};

obj.age = undefined;
console.log(obj); // { name: 'John', age: undefined }

Leave a Reply