Accessing object properties

In JavaScript, you can access the properties of an object using either dot notation or bracket notation.

Dot notation

Dot notation is the most common way to access an object property. To access a property using dot notation, you simply write the name of the object followed by a dot . and then the name of the property you want to access. Here's an example:

Loading Code . . .

In the example above, we've created an object called person with three properties: firstName, lastName, and age. We then use dot notation to access the firstName and age properties of the person object.

Bracket notation

Bracket notation is another way to access object properties. Instead of using a dot to access the property, you use square brackets [ ]. Inside the brackets, you write the name of the property as a string. Here's an example:

Loading Code . . .

In this example, we're accessing the same firstName and age properties, but this time we're using bracket notation instead of dot notation.

One advantage of using bracket notation is that you can use variables to access object properties. Here's an example:

Loading Code . . .

In this example, we've assigned the string "firstName" to a variable called property. We can then use this variable to access the firstName property of the person object using bracket notation.

Why would you want to do this? Well, sometimes you don't know the name of the property you want to access until you've run your code. For example, you might want to access a property that's stored in a variable. In this case, you can use bracket notation to access the property.

In summary, you can access object properties in JavaScript using either dot notation or bracket notation. Dot notation is the most common way to access properties, but bracket notation can be useful when you need to use variables to access properties.

Challenge

Create a function called getPersonInfo that takes an object as the first argument and a string as the second argument. The function should return the value of the property with the name that matches the string. For example, if you call the function like this:

Loading Code . . .

The function should return "John".

Loading...

© 2024 - ®Mewters