Code highlights logo

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:

1const person = {
2 name: 'John Doe',
3 age: 30,
4 occupation: 'Web Developer'
5};
6
7const propertyName = 'name';
8console.log(person[propertyName]); // Output: John Doe
9
10const propertyToAccess = 'age';
11console.log(person[propertyToAccess]); // Output: 30

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

  1. 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.
    1const person = {
    2 name: 'John',
    3 age: 30
    4};
    5
    6const propertyName = 'name';
    7console.log(person[propertyName]); // Output: 'John'
    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.
  2. 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.
    1const user = {
    2 'first name': 'John',
    3 'last name': 'Doe',
    4 '123 age': 30
    5};
    6
    7console.log(user['first name']); // Output: 'John'
    8console.log(user['last name']); // Output: 'Doe'
    9console.log(user['123 age']); // Output: 30
    Here, we use bracket notation to access properties with special characters and spaces in their names.

Instructions

1.

In the student object, use bracket notation to access and console log the value of the name property.

2.

Create a variable called property and set it equal to "grade".

3.

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

Course content