How to remove a property from an object in JavaScript?

featured Image

In this short article, we will learn how to delete a property from a JavaScript object.

JavaScript objects are collections of different properties and types, each property has a name and a value.

Using delete operator

To delete a property from a given JavaScript object we can use the delete operator. In JavaScript, the delete operator is use to remove a property from an object.

Syntax:

delete object.property
//or
delete object['property']

Suppose we have an object person, with name, address, and occupation as properties.

const person = {
  name : 'John',
  address: 'New York',
  occupation: 'Engineer'
}

So to remove the property occupation from the person object we can use delete like this.

const person = {
  name : 'John',
  address: 'New York',
  occupation: 'Engineer'
}
delete person.occupation

console.log(person)

Output:

{ name: 'John', address: 'New York' }

As you can see, the object no longer have the occupation property.

You can also use the square bracket instead of using dot property accessor.

delete person['occupation']

However, if you don’t want to delete the property and just remove the value of it, you can just set the property value to undefined .

Setting JavaScript Object Property to undefined

Setting the property to undefined is considered to be much faster than deleting the whole property if you are operating on a large number of objects.

To set the property to undefined, you can use a dot or square bracket property accessor.

Example:

const person = {
  name : 'John',
  address: 'New York',
  occupation: 'Engineer'
}

person.occupation = undefined 
//OR
person['occupation'] = undefined

console.log(person)

Output:

{ name: 'John', address: 'New York', occupation: undefined }

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more