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:
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:
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.
If you try to read a property of something that's undefined, you get an error:
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.