Conteúdo do Curso
JavaScript Data Structures
JavaScript Data Structures
Accessing Object Properties
We will explore two methods for accessing object properties: dot notation and square brackets. These methods allow you to retrieve specific values from objects, and we'll discuss scenarios in which each method is commonly used.
Dot Notation to Access Properties
The primary and most frequently used method for accessing object properties is dot notation. With this approach, we access a property by specifying the object's name followed by a dot and the property name.
Let's consider an example where we use an object to represent an employee and access its properties using dot notation:
const employee = { companyName: "Schuster, Mertz and Marks", name: "Miss Alma Boyer", address: "2277 Karine Plains", workedYears: 4, remote: false, }; console.log(employee.name); // Output: Miss Alma Boyer console.log(employee.address); // Output: 2277 Karine Plains console.log(employee.lastName); // Output: undefined
Note
- If you attempt to access a property that does not exist, JavaScript will return
undefined
;undefined
is not outputted when you run the code.
Accessing Properties Through Square Brackets
The second method for accessing object properties is through square brackets. This syntax involves specifying the object's name, followed by square brackets with the property name as a string inside them.
This approach is used less frequently than dot notation but is essential in cases where the property name is not known in advance or is stored in a variable, such as a function parameter.
Here's an example using the same employee
object:
const employee = { companyName: "Schuster, Mertz and Marks", name: "Miss Alma Boyer", address: "2277 Karine Plains", workedYears: 4, remote: false, }; console.log(employee["name"]); // Output: Miss Alma Boyer console.log(employee["address"]); // Output: 2277 Karine Plains console.log(employee["lastName"]); // Output: undefined
This method provides the property name as a string within square brackets. It allows for dynamic property access, which can be helpful when dealing with more complex data.
Accessing Nested Properties
Let's explore how to access nested properties using dot notation with the following example.
With dot notation, we specify the path to the desired property, separated by dots. Let's consider an example with a course object:
const course = { courseName: "Applied Science", courseDuration: "48 hours", author: { position: "Nuclear Physicist", age: 43, name: { first: "Mattie", last: "Crooks", }, }, }; console.log(course.author.position); // Output: Nuclear Physicist console.log(course.author.age); // Output: 43 console.log(course.author.name.first); // Output: Mattie console.log(course.author.name.last); // Output: Crooks
In this example, we access properties at different levels of nesting within the product object.
Obrigado pelo seu feedback!