How to Add Property to Object in JavaScript: Simple Guide
To add a property to an object in JavaScript, use
object.propertyName = value or object['propertyName'] = value. Both ways create a new property if it doesn't exist or update it if it does.Syntax
You can add or update a property in an object using two main ways:
- Dot notation:
object.propertyName = value; - Bracket notation:
object['propertyName'] = value;
Dot notation is simple and readable but only works with valid identifier names. Bracket notation works with any string key, including those with spaces or special characters.
javascript
object.propertyName = value;
object['propertyName'] = value;Example
This example shows how to add new properties to an object using both dot and bracket notation.
javascript
const person = { name: 'Alice' }; // Add age using dot notation person.age = 30; // Add city using bracket notation person['city'] = 'New York'; console.log(person);
Output
{"name":"Alice","age":30,"city":"New York"}
Common Pitfalls
Some common mistakes when adding properties to objects include:
- Using dot notation with invalid property names (like spaces or starting with numbers) causes errors.
- Forgetting quotes in bracket notation when the property name is a string.
- Trying to add properties to
nullorundefinedvalues causes runtime errors.
Always ensure the object exists before adding properties.
javascript
const obj = {}; // Wrong: property name with space using dot notation (causes error) // obj.first name = 'John'; // SyntaxError // Right: use bracket notation with quotes obj['first name'] = 'John'; console.log(obj);
Output
{"first name":"John"}
Quick Reference
Summary tips for adding properties to objects:
- Use dot notation for simple, valid property names.
- Use bracket notation for dynamic or complex property names.
- Always check the object is not
nullorundefinedbefore adding properties. - Adding a property that already exists updates its value.
Key Takeaways
Use dot notation or bracket notation to add properties to JavaScript objects.
Bracket notation allows property names with spaces or special characters.
Adding a property that exists updates its value; otherwise, it creates a new property.
Avoid adding properties to null or undefined to prevent errors.
Always ensure property names are valid for the chosen notation.