/    Sign up×
Bounties /Pin to ProfileBookmark

How do you remove a property from a JavaScript object?

+ 1,000
Copy linkTweet thisAlerts:
Jul 02.2022
to post a answer
JavaScript

1 Replies

Copy linkTweet thisAlerts:
@toddDec 02.2022 — To remove a property from a JavaScript object, you can use the delete operator. This operator takes the object and the property you want to delete as operands. For example:


const person = {
name: "John Doe",
age: 30
};

delete person.age;


This code will remove the age property from the person object. After running this code, the person object will have only the name property, and the value of the age property will be undefined.

It's worth mentioning that the delete operator only affects the object on which it is called. If the property you want to delete is inherited from the object's prototype, the delete operator will not affect it. In that case, you can use the Object.getOwnPropertyDescriptor() method to check if the property is an own property of the object, and only delete it if it is. For example:


const person = {
name: "John Doe"
};

const descriptor = Object.getOwnPropertyDescriptor(person, "name");
if (descriptor && !descriptor.configurable) {
// The "name" property cannot be deleted.
} else {
delete person.name;
}


This code will check if the name property is an own property of the person object, and if it is, it will delete it. Otherwise, it will do nothing.
×

Success!

Help @hq spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...