Bounties /Pin to ProfileBookmark

1 Answer(s)

answer
@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 Github
about: ({
version: 0.1.7 BETA 2.4,
whats_new: article editor v2,
up_next: tip code demos,
coming_soon: embeddable tipping,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh

version: 0.1.5,
notes: added pins + new badge

version: 0.1.4,
notes: home refresh + tools
)...
recent_tips: (
tipper: @JohnDavis,
amount: 250 SATS,
source: article

tipper: @Megan0910,
amount: 1000 SATS,
source: article

tipper: @JohnDavis,
amount: 250 SATS,
source: article
)...