DEV Community

Cover image for Different Ways to Access Object Properties in JavaScript
Surbhi Dighe
Surbhi Dighe

Posted on

Different Ways to Access Object Properties in JavaScript

There are different ways to access object properties in JavaScript

1. Dot notation - One common way to access object properties in JavaScript is through dot notation. This involves specifying the property name after the object name, with both separated by a dot.

const name = {
  firstName: "Surbhi",
  lastName: "Dighe
};
console.log(name.firstName);  // Output: "Surbhi"
console.log(name.lastName);   // Output: "Dighe"
Enter fullscreen mode Exit fullscreen mode

2. Bracket notation - Another way to access object properties is through bracket notation, which involves specifying the property name as a string inside square brackets.

const name = {
  firstName: "Surbhi",
  lastName: "Dighe
};
console.log(name["firstName"]);  // Output: "Surbhi"
console.log(name["lastName"]);   // Output: "Dighe"
Enter fullscreen mode Exit fullscreen mode

3. Object destructuring - It allows you to create variables that correspond to the properties of an object. By using object destructuring, you can easily extract specific values from an object and use them in your code.

const name = {
  firstName: "Surbhi",
  lastName: "Dighe
};
const { firstName, lastName } = name;
console.log(firstName);  // Output: "Surbhi"
console.log(lastName);   // Output: "Dighe"
Enter fullscreen mode Exit fullscreen mode

Although there are various ways to access object properties in JavaScript, the dot notation and bracket notation are the most frequently used.

Object destructuring is useful when you need to create variables from object properties.

Top comments (0)