How to remove a property from a JavaScript object? (delete, spread and other methods)
Hello everyone! I just started learning JavaScript and encountered a problem. I have an object that contains user data:
```javascript
const user = {
name: 'Alexey',
age: 30,
email: 'alex@example.com',
password: 'secret123',
role: 'admin'
};
```
I need to remove the `password` property from this object before sending the data to the client (to avoid exposing the password). I tried assigning `undefined`:
```javascript
user.password = undefined;
```
But this does not remove the property — it just becomes `undefined`. When serializing to JSON (JSON.stringify) it disappears, but the key remains in the object itself. And if I iterate over the object with `for...in`, `password` still shows up.
I've heard about the `delete` operator, but I'm confused because some people say it's slow and should be avoided. Also, I read that `delete` doesn't work on properties inherited from the prototype. Are there other ways to remove a property? For example, using the spread operator to create a new object without the property? What is the best practice in modern JavaScript?
No answers yet.
Log in to leave an answer