DEV Community

Lokesh_Choudhary
Lokesh_Choudhary

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 :-

1.
const obj = {name:'cool'};
console.log(obj.name);
Enter fullscreen mode Exit fullscreen mode
2.
const obj = {name:'cool'};
console.log(obj[name]);
Enter fullscreen mode Exit fullscreen mode

Now using the delete operator:

const obj = {name:'cool', age:20};
delete obj.name;
or
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;
console.log(name);
console.log(remainingProp);
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.

Latest comments (0)