Essential JavaScript

Going Further

Nested Objects

Object properties can contain any kind of value. That includes other objects!

This allows us to organize our data better:

const book = { title: 'Gone with the Wind', genre: 'Epic Historical Romance', author: { name: 'Margaret Mitchell', nationality: 'American', }, };

Creating Nested Objects

We can create nested objects all at once like the example above.

We could also create individual objects and then merge them together:

const margaretMitchell = { name: 'Margaret Mitchell', nationality: 'American', }; const book = { title: 'Gone with the Wind', genre: 'Epic Historical Romance', author: margaretMitchell, };

Both examples will create an identical object.

Accessing Nested Object Properties

To access the properties inside nested objects, we chain property names together:

const book = { title: 'Gone with the Wind', genre: 'Epic Historical Romance', author: { name: 'Margaret Mitchell', nationality: 'American', }, }; console.log(book.title); // "Gone with the Wind" console.log(book.author.name); // "Margaret Mitchell"

Learning Goals

  • I can create objects with other objects as properties

  • I can access the properties of a nested object

Code Editor

Click "Run Code" to execute your JavaScript in a secure sandbox and see the output below.

Console Output

// Console output will appear here...

0 output lines