DEV Community


Posted on


How To Remove a Property From a JavaScript Objects πŸ‘¨β€πŸŽ“πŸ€“.

What is a Object in JavaScript:

Definition by MDN

*Objects in JavaScript, just as in many other programming languages, can be compared to objects in real life. The concept of objects in JavaScript can be understood with real life, tangible objects.

In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc. The same way, JavaScript objects can have properties, which define their characteristics.*

Source: link here

How to delete a property in a object:-

1. Using the delete operator:-

It is a special operation that removes a property from an object.

And before I talk about how it is used , Did you know there are two ways to access a object property :-

const obj = {name:'cool'};
Enter fullscreen mode Exit fullscreen mode
const obj = {name:'cool'};
Enter fullscreen mode Exit fullscreen mode

Now using the delete operator:

const obj = {name:'cool', age:20};
delete obj[name]
Enter fullscreen mode Exit fullscreen mode

delete operator is mutable , just a fancy of saying that it modify the object permanently.

2. Using destructuring:-

Destructuring in Javscript is used to unpack values or properties from Arrays or objects.

const obj = {name:'cool', age:20};
const {name, age} = obj;
Enter fullscreen mode Exit fullscreen mode

Same way to delete/remove use the syntax:-

const {prop,...restObj} = obj;

const obj = {name:'cool', age:20 , class:A};
const {name, ...remainingProp} = obj;
Enter fullscreen mode Exit fullscreen mode

This way to do this immutable that means the original object remains same as before but still we get access to single property and other remaining properties , in this case name is not present in the remainingProp.

Top comments (0)