Code highlights logo

Learn

Objects

Nested Objects

Nested objects are objects that are stored as values within other objects. This means that we can have an object property that itself is an object. This nesting can be performed to any depth, creating a hierarchical structure of objects.

Creating Nested Objects

To create a nested object, we simply assign an object as a value to a property within another object. This can be done during the object's initialization or later by assigning a new object to an existing object property.

1let myObject = {
2 property1: value1,
3 property2: {
4 nestedProperty1: nestedValue1,
5 nestedProperty2: nestedValue2
6 }
7};

Accessing Nested Object Properties

To access properties within a nested object, we use dot notation or bracket notation multiple times, chaining along the properties of each level.

1console.log(myObject.property2.nestedProperty1); // Output: nestedValue1
2
3// or
4
5console.log(myObject["property2"]["nestedProperty1"]); // Output: nestedValue1

Modifying Nested Object Properties

We can modify the properties of a nested object by simply accessing them and assigning a new value.

1myObject.property2.nestedProperty1 = newValue;
2
3// or
4
5myObject["property2"]["nestedProperty1"] = newValue;

Instructions

1.

Access the value of the city property in the address object and console.log it.

2.

Add a new property zipCode with the value "10001" to the address object.

3.

Console.log the person object to see the updated values.

Sign up to start coding

Already have an account?

Sign In

Course content