프로퍼티 (Properties)

In JavaScript, properties are values associated with an object. They define the characteristics and behavior of an object. Properties can be primitive values like strings, numbers, booleans, or they can be objects themselves.

Accessing properties

There are two common ways to access properties in JavaScript: dot notation and bracket notation. Dot notation is used when you know the name of the property you want to access.

const person = {
  name: 'John',
  age: 30,
  occupation: 'Developer'
};

console.log(person.name); // Output: John
console.log(person.age); // Output: 30

In the example above, person is an object with properties name, age, and occupation. By using dot notation, we can access the values of these properties.

Bracket notation is used when the property name is stored in a variable or when the property name contains special characters.

const propertyName = 'age';
console.log(person[propertyName]); // Output: 30

const specialPropertyName = 'occu*pation';
console.log(person[specialPropertyName]); // Output: Developer

Modifying properties

Properties in JavaScript can be modified by assigning new values to them. This can be done using either dot notation or bracket notation.

person.name = 'Jane';
console.log(person.name); // Output: Jane

person['age'] = 31;
console.log(person.age); // Output: 31

In the example above, we modify the name property to ‘Jane’ and the age property to 31.

Adding new properties

New properties can be added to an existing object simply by assigning a value to a property name that doesn’t exist.

person.gender = 'Female';
console.log(person.gender); // Output: Female

In the code snippet above, we add a new property gender with the value ‘Female’ to the person object.

Deleting properties

Properties can be removed from an object using the delete keyword followed by the property name.

delete person.occupation;
console.log(person.occupation); // Output: undefined

In the example above, we delete the occupation property from the person object.

Conclusion

Understanding properties in JavaScript is vital for working with objects. With properties, we can define various characteristics and behaviors of an object. We can access, modify, add, and delete properties to manipulate objects in our JavaScript programs.