Imagine you want to store information about a book: its title, author, and year published. Why is using an object helpful compared to separate variables?
Think about how you would carry multiple pieces of information together.
Objects group related data into one place, so you can handle all details about something as a single unit. This is easier than managing many separate variables.
Look at this JavaScript code that uses an object to store a person's info. What will it print?
const person = { name: 'Anna', age: 30 }; console.log(person.name + ' is ' + person.age + ' years old.');
Access object properties with dot notation.
The code accesses the name and age properties of the person object and prints them in a sentence.
What will this code print when trying to access a property that does not exist in the object?
const car = { brand: 'Toyota', year: 2020 }; console.log(car.color);
Think about what JavaScript returns when a property is missing.
Accessing a property that does not exist on an object returns undefined in JavaScript.
You want to store a person's name and age. Why is an object better than an array for this?
Think about how you find data by position or by name.
Objects let you use names for each piece of data, making code easier to read and less error-prone than using array positions.
Consider this object with nested objects. What will the code print?
const user = { id: 1, profile: { username: 'coder', details: { age: 25 } } }; console.log(user.profile.details.age);
Access nested properties step by step using dot notation.
The code accesses profile then details then age, which is 25.