Nested Objects and Arrays of Objects

Grade 8, page 7 of 13. A one-minute read.

Objects can contain other objects and arrays. And arrays can contain objects. You can nest them as deeply as you like to describe complex things:

JavaScript
const user = {
  username: "lucas_codes",
  age: 19,
  address: {
    city: "Paris",
    country: "France",
  },
  hobbies: ["football", "coding", "drawing"],
};

console.log(user.address.city);
console.log(user.hobbies[1]);
console.log(user.hobbies.length);

It prints

Paris
coding
3

To dig into nested data, just keep chaining: user.address.city means "go into user, then into address, then read city." And user.hobbies[1] means "go into user, get the hobbies array, and take item 1."

Arrays of objects

This is one of the most common shapes of data you'll ever see. Almost every list in every app (contacts, products, messages, tweets) is an array of objects:

JavaScript
const students = [
  { name: "Mia", score: 88 },
  { name: "Omar", score: 72 },
  { name: "Zoe", score: 95 },
  { name: "Sam", score: 61 },
];

for (const student of students) {
  const result = student.score >= 70 ? "passed ✅" : "needs help 📚";
  console.log(`${student.name}: ${student.score} (${result})`);
}

console.log(`First student: ${students[0].name}`);

It prints

Mia: 88 (passed ✅)
Omar: 72 (passed ✅)
Zoe: 95 (passed ✅)
Sam: 61 (needs help 📚)
First student: Mia

Get comfortable with this pattern, because you'll see it every day as a JavaScript developer. When you load data from the internet in College, it'll almost always arrive as an array of objects.

Watch outReading into nothing

If you try to read a property of something that's undefined, you get an error:

JavaScript
const user = { username: "lucas_codes" };
console.log(user.address.city);

It stops with an error

Uncaught TypeError: Cannot read properties of undefined (reading 'city')

user.address is undefined (there's no address), and you can't read city from undefined. This is one of the most common errors in all of JavaScript! You'll learn a neat way to protect against it, called optional chaining (user.address?.city), in Grade 13.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning