Suggest an editImprove this articleRefine the answer for “New property in an object”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)You can add a new property to an object via a **dot** (`obj.key = value`), **square brackets** (`obj['key'] = value`), **`Object.assign()`**, the **spread operator**, or **`Object.defineProperty()`**. **Key point:** every method except the spread operator mutates the original object; spread creates a new copy.Shown above the full answer for quick recall.Answer (EN)Image## 1. Via a **dot** (`.`) ```javascript const user = { name: 'Tim' }; user.age = 25; // add a new property console.log(user); // { name: 'Tim', age: 25 } ``` Works if the property name is a **valid identifier** (no spaces, no special characters, does not start with a digit). --- ## 2. Via **square brackets** (`[]`) ```javascript const user = { name: 'Tim' }; user['city'] = 'Kyiv'; console.log(user); // { name: 'Tim', city: 'Kyiv' } ``` This way works well when: - the key is stored in a **variable**: ```javascript const key = 'email'; user[key] = 'tim@mail.com'; ``` - or contains **invalid characters**: ```javascript user['favorite color'] = 'blue'; ``` --- ## 3. With **Object.assign()** ```javascript const user = { name: 'Tim' }; Object.assign(user, { age: 25, city: 'Kyiv' }); console.log(user); // { name: 'Tim', age: 25, city: 'Kyiv' } ``` You can add several properties at once. The method mutates the original object. --- ## 4. With the **spread operator (**`...`**)** - creates a new object ```javascript const user = { name: 'Tim' }; const updatedUser = { ...user, age: 25 }; console.log(updatedUser); // { name: 'Tim', age: 25 } ``` The original object **is not changed** - a **new copy** is created (an immutable approach). --- ## 5. Via **Object.defineProperty()** (rarer, but flexible) ```javascript const user = {}; Object.defineProperty(user, 'age', { value: 25, writable: true, enumerable: true, configurable: true }); console.log(user); // { age: 25 } ``` Lets you fine-tune the property: for example, make it read-only or hidden when iterated over. --- ## SUMMARY | Way | Mutates the original object | Best for | |---|---|---| | `obj.key = value` | Yes | simple cases | | `obj['key'] = value` | Yes | dynamic keys | | `Object.assign()` | Yes | bulk additions | | `{ ...obj, key: value }` | No | creating a new object | | `Object.defineProperty()` | Yes | special property configuration |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.