객체 속성 접근 방법

When working with objects in JavaScript, one of the fundamental operations is accessing and manipulating their properties. In this blog post, we will explore the various ways to access object properties in JavaScript, along with examples for each method.

Dot notation

The most common way to access an object property is by using dot notation. With dot notation, you can directly reference the property name after the object name.

const person = {
  name: "John",
  age: 25,
  occupation: "Developer"
};

console.log(person.name); // Output: John
console.log(person.age); // Output: 25
console.log(person.occupation); // Output: Developer

Bracket notation

Another way to access object properties is by using bracket notation. With bracket notation, you enclose the property name inside square brackets and use them after the object name.

const person = {
  name: "John",
  age: 25,
  occupation: "Developer"
};

console.log(person["name"]); // Output: John
console.log(person["age"]); // Output: 25
console.log(person["occupation"]); // Output: Developer

Bracket notation allows you to dynamically access object properties using variables.

const person = {
  name: "John",
  age: 25,
  occupation: "Developer"
};

const propertyName = "name";
console.log(person[propertyName]); // Output: John

Computed property names

ES6 introduced computed property names, which provide a more concise way to define object properties. You can use square brackets around an expression to compute the property name.

const propertyName = "name";

const person = {
  [propertyName]: "John",
  age: 25,
  occupation: "Developer"
};

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

Computed property names are useful when you need to dynamically generate object properties based on variables or expressions.

Nullish coalescing operator

In JavaScript, accessing nested object properties can be challenging, especially when dealing with null or undefined values. The nullish coalescing operator (??) is a recent addition that provides a concise way to handle undefined or null values.

const person = {
  name: "John",
  age: 25,
  occupation: null
};

console.log(person.occupation ?? "Unknown"); // Output: Unknown

The nullish coalescing operator evaluates to the right-hand side value only if the left-hand side value is null or undefined. Otherwise, it returns the left-hand side value.

These are some of the common methods for accessing object properties in JavaScript. By understanding these different approaches, you can efficiently manipulate and work with object data in your JavaScript code.

Remember to use dot notation for direct property access, bracket notation for dynamic access or when the property name contains special characters, computed property names for dynamically generating properties, and the nullish coalescing operator for handling null or undefined values.