How to add a key-value pair to a JavaScript object?
Hello everyone! I just started learning JavaScript and encountered this problem. I have an empty object that I created like this:
```javascript
let myObject = {};
```
Or, for example, I already have an object with some data:
```javascript
let user = {
name: "Anna",
age: 25
};
```
Now I need to dynamically add a new property to this object, for example, "email" or "isAdmin". I tried several methods, but I'm not sure which one is correct and which is better to use in different situations.
Here's what I tried:
1. Simply assign a value using dot notation: `user.email = "anna@example.com";`
2. Use square brackets: `user["email"] = "anna@example.com";`
3. Use the `Object.assign()` method
4. Use the spread operator: `user = {...user,
No answers yet.
Log in to leave an answer
Blogs