Skip to content

How to remove a property from an object in JavaScript?

In this article, you will learn different ways to remove a property from an object in JavaScript.

delete operator

The delete operator removes a given property from an object. It deletes both the value of the property and the property itself. On successful deletion, it will return true, else false will be returned. It doesn’t free up the memory occupied by the property.

Any property declared with var cannot be deleted from the global scope or from a function’s scope. Any property declared with let or const cannot be deleted from the scope within which they were defined.

Syntax

delete object.property
delete object['property']

Examples

const obj  = {name:"Anand", class:"X", score:89};

delete obj.class;

console.log(obj);

//{name: "Anand", score: 89}



delete obj[score];

console.log(obj);

// {name: "Anand"}

Reflect.deleteProperty()

Reflect object was introduced in ES6. It can be used to delete object property by calling Reflect.deleteProperty() function with target object and property key as parameters.

Syntax

Reflect.deleteProperty(obj, key);

Example

const obj  = {name:"Anand", class:"X", score:89};

Reflect.deleteProperty(obj, 'class')

console.log(obj)

//{name: "Anand", score: 89}

The most ineffective way is to set undefined to the property and convert it to string using JSON.stringify() and converting it back to JSON using JSON.parse()

let obj  = {name:"Anand", class:"X", score:89};

obj.class = undefined;
obj = JSON.parse(JSON.stringify(obj));

console.log(obj);

//{name: "Anand", score: 89}

I suggest not to use the above one.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.