자바스크립트 객체 속성 추가(Property Adding)

In JavaScript, objects are a fundamental part of the language and allow us to store and manipulate data. One of the key features of objects is the ability to add or modify properties dynamically. This flexibility makes JavaScript powerful for building various applications.

Adding Properties to Objects

To add a new property to an existing object, we can use dot notation or square bracket notation. Let’s consider an example where we have an object representing a person:

let person = {
  name: 'John',
  age: 30,
};

person.occupation = 'Engineer';
person['country'] = 'USA';

In the code snippet above, we add two properties to the person object using both notations. The occupation property is added using dot notation, while the country property is added using square bracket notation.

Accessing the Newly Added Properties

Once we have added the properties to the object, we can access their values using the same notation used for adding them. For example:

console.log(person.occupation);   // Output: Engineer
console.log(person['country']);   // Output: USA

We can retrieve and use the values of the newly added properties by referencing them with dot notation or square bracket notation.

Updating Existing Properties

In addition to adding new properties, we can also update existing properties of an object. This can be done by simply assigning a new value to the desired property:

person.name = 'Jane';
person['age'] = 35;

In the code snippet above, we update the name property using dot notation and the age property using square bracket notation.

Conclusion

The ability to dynamically add or update properties in JavaScript objects provides great flexibility when working with data. Whether it’s adding new properties to store additional information or updating existing properties with new values, JavaScript allows us to manipulate objects in a straightforward manner.

Remember that dot notation is usually used when we know the property name beforehand, while square bracket notation is useful when the property name is stored in a variable or needs to be dynamically determined at runtime.

By mastering the techniques for adding and updating properties, you can unlock the full potential of JavaScript objects in your applications. Happy coding!