JavaScriptLesson 8 of 10Jump to practice
Objects
Group related values under names, and store lists of records as arrays of objects.
An array is a list in order. An object groups related values under names, called keys.
const student = {
name: "Emma",
age: 21,
city: "Seattle",
subjects: ["English", "Math"],
};
Each key: value pair is a property. Values can be anything: numbers, strings, arrays, even other objects.
Reading and changing properties
<script>
const student = { name: "Emma", age: 21, city: "Seattle" };
// Dot notation
console.log(student.name);
// Bracket notation: useful when the key is in a variable
const key = "city";
console.log(student[key]);
// Change and add properties
student.age = 22;
student.email = "rina@example.com";
console.log(student);
// A missing property is undefined
console.log(student.phone);
</script>Functions inside objects
A function stored in an object is called a method. Inside it, this means the object itself.
const counter = {
count: 0,
increase() {
this.count++;
},
};
counter.increase();
console.log(counter.count); // 1
Lists of records
Most real data is an array of objects: products, users, posts. Combine what you’ve learned to work with it.
<script>
const products = [
{ name: "Notebook", price: 3, inStock: true },
{ name: "Pen", price: 1, inStock: false },
{ name: "Backpack", price: 45, inStock: true },
];
for (const p of products) {
console.log(p.name + ": $" + p.price);
}
const available = products.filter((p) => p.inStock);
console.log("In stock:", available.map((p) => p.name).join(", "));
const total = products.reduce((sum, p) => sum + p.price, 0);
console.log("Everything costs $" + total);
</script>Practice
Check what you just learned. Fill in the missing code, then answer the quiz.
Exercise 1Solved
Print the user's city.
const user = { name: "Emma", city: "Seattle" }; console.log(user.);Exercise 2Solved
Read the property whose name is stored in the variable
key.const key = "age"; console.log(user);Use square brackets, without quotes around the variable.
Exercise 3Solved
Separate the two properties correctly.
const book = { title: "The Great Gatsby" author: "F. Scott Fitzgerald" };
Finish the practice to complete this lesson.
Sign in to keep your progress on any device.