11 / 12 · Intro
Objects
An object groups related values under names. In { name: "Coco", age: 3 }, pet.name gives "Coco" and pet.age gives 3.
Jump to the 10 practice questionsYou will learn
- Group values under names in an object and read them
- Change and add properties, and use arrays of objects
- Call a method that uses this
Before this: Functions
1Explain
Values with labels
An object is written in curly braces, with each property as key: value and commas between them. A trailing comma after the last property is allowed. To read a property, write the object, a dot and the key: pet.name. The other form uses square brackets and a string, pet["kind"]. Brackets are needed when the key is stored in a variable, as in pet[field], or when it contains a space.
The object is drawn as key → value rows. pet.name and pet["kind"] read two of them.
const pet = {name: "Coco",kind: "cat",age: 3,};console.log(pet.name); // Cococonsole.log(pet["kind"]); // catconsole.log(pet.age + 1); // 4
Coco cat 4
2Explore
Read a property
A missing property reads as undefined. The whole object prints in the compact form used on this site.
const pet = { name: "Coco", kind: "cat", age: 3 };
console.log(pet.name);Coco3Problem
Bracket notation
const car = { brand: "Kia", year: 2020 };
console.log(car["brand"]);Hint
car["brand"] reads the same property as car.brand.
Solution
Answer: Kia
Bracket notation with the string "brand" reads the same property as car.brand.
4Problem
A property that is not there
What does this print?
const car = { brand: "Kia" };
console.log(typeof car.color);Hint
Reading a missing property does not stop the program.
Solution
Answer: undefined
A missing property reads as undefined, so its type is "undefined".
5Explain
Changing and adding properties
Assign to a property to change it, and assign to a new key to add one. As with arrays, this works even when the object was declared with const, because the variable still points to the same object.
Watch the rows: += changes score, a new key adds level, and delete removes it again.
const player = { name: "Sam", score: 0 };player.score += 10;player.level = 2;console.log(`${player.name} ${player.score} ${player.level}`); // Sam 10 2delete player.level;console.log(player.level); // undefined
Sam 10 2 undefined
6Problem
How many keys?
What does this print?
const p = { name: "Lee" };
p.age = 40;
console.log(Object.keys(p).length);Hint
name was there, and age was added.
Solution
Answer: 2
Adding age gives two keys: name and age.
7Explain
Lists of objects
Arrays and objects combine naturally. An array of objects is how most programs hold records: a shopping basket, a class list, a set of search results. You loop over the array and read the properties you need from each object.
Each round, line is the next object in the array, and line.price is added to total.
const basket = [{ item: "pen", price: 2 },{ item: "book", price: 12 },{ item: "bag", price: 25 },];let total = 0;for (const line of basket) {total += line.price;}console.log("Total:", total); // Total: 39
Total: 39
8Problem
Add the n values
What does this print?
const items = [{ n: 2 }, { n: 5 }, { n: 1 }];
let t = 0;
for (const it of items) {
t += it.n;
}
console.log(t);Hint
Read it.n from each object: 2, 5, 1.
Solution
Answer: 8
2 + 5 + 1 = 8.
9Explain
Methods and this
A property whose value is a function is called a method. You have been calling methods all along: console.log is the log method of the console object, and Math.round is the round method of Math. Inside a method, the keyword this refers to the object the method was called on, so a method can read its own object's properties. Finally, Object.keys(pet) gives an array of the keys, here ["name", "kind", "age"], which is useful for looping over every property.
const counter = {
count: 0,
add() {
this.count++;
},
};
counter.add();
counter.add();
console.log(counter.count); // 2210Practice
Describe the pet
Use the three properties and a template literal to print Coco is a 3 year old cat.
Coco is a 3 year old catconst pet = { name: "Coco", kind: "cat", age: 3 };
console.log(pet.name);
Hint
Inside the template, read each property through pet: ${pet.name}.
A solution
const pet = { name: "Coco", kind: "cat", age: 3 };
console.log(`${pet.name} is a ${pet.age} year old ${pet.kind}`);11Practice
Total of the basket
Add a loop that adds every price to total, so the program prints Total: 39.
Total: 39const basket = [
{ item: "pen", price: 2 },
{ item: "book", price: 12 },
{ item: "bag", price: 25 },
];
let total = 0;
// Loop over basket and add up the prices.
console.log("Total:", total);
Hint
for (const line of basket) gives each object; add line.price with +=.
A solution
const basket = [
{ item: "pen", price: 2 },
{ item: "book", price: 12 },
{ item: "bag", price: 25 },
];
let total = 0;
for (const line of basket) {
total += line.price;
}
console.log("Total:", total);12Explain
Common mistakes
const user = { name: "Ana" };
console.log(user.adress.city);TypeError: Cannot read properties of undefined (reading 'city') (line 2)
- The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
- After the colon: what went wrong, usually with the name involved.
- The line number shows where the program stopped. A SyntaxError stops it before any line runs.
user.adress is misspelled, so it is undefined, and undefined has no city.
const pet = { name: "Coco" age: 3 };SyntaxError: Unexpected identifier 'age'
- The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
- After the colon: what went wrong, usually with the name involved.
- The line number shows where the program stopped. A SyntaxError stops it before any line runs.
Properties are separated by commas. Without the comma after "Coco" the object is not valid JavaScript.
13
Summary
- Objects hold key: value properties in { }.
- Read with obj.key or obj["key"]; brackets for keys in variables.
- Assign to change or add a property; missing keys read as undefined.
- Arrays of objects hold records; loop and read each property.
- A method is a function property; this is its object.