Learn
Objects
Bracket Notation
Another way to access properties of an object is by using the bracket notation. The bracket notation allows us to access properties dynamically, using variables or expressions as property names.
Here is an example:
In this example, we have defined a variable propertyName
and assigned it the value of 'name'
. We can then use the bracket notation to access the name
property of the person
object by passing propertyName
within the brackets.
When to Use Bracket Notation
- Dynamic Property Access: If the property we want to access is stored in a variable or is dynamically determined at runtime, bracket notation is the way to go. We can use the value of the variable inside the brackets to access the property.
In this example, we store the property name in the
propertyName
variable and use it inside the bracket notation to access the corresponding property value. - Special Characters and Spaces: If a property name contains special characters, spaces, or starts with a number, dot notation won't work. We have to use bracket notation to access such properties.
Here, we use bracket notation to access properties with special characters and spaces in their names.
Instructions
In the student
object, use bracket notation to access and console log the value of the name
property.
Create a variable called property
and set it equal to "grade"
.
Use the property
variable and bracket notation to access and console log the value of the grade
property. (student[property]
)
Sign up to start coding
Already have an account?
Sign In