Lesson 2 · Unit 04
Objects
Values under named keys: reading, changing, nesting, unpacking and copying
What you practise
- Literals, dot and bracket access, adding and deleting keys, nesting, destructuring, spread,
Object.keysandObject.entries, a missing key givesundefined
Try a question from this lesson
Pick one
An array numbers its values. An object gives each value a name instead. What do you think this prints?
const book = {
title: "Dune",
pages: 412,
};
console.log(book.pages);Correct answer
412
Why
The object holds two values, each stored under a name. book.pages asks for the value stored under pages. The names are called keys, and the dot reads "the pages of book".
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Objects
An object is a set of key: value pairs in curly brackets. It describes one thing with several named parts.
Read a value with a dot: user.name.
Square brackets do the same with the key as a string. Use them when the key is held in a variable.
const user = { name: "Ana", age: 30 };
console.log(user.name); // Ana
console.log(user["age"]); // 30
const key = "name";
console.log(user[key]); // AnaConcept
Changing an object
Assign to a key to add it or to change its value. delete removes a key and its value.
Object.keys(obj) gives an array of the keys, in the order they were added.
That array is the way in for a loop: go through the keys, and look each value up.
const stock = { tea: 4, milk: 0 };
stock.jam = 2; // add a key
stock.tea = 5; // change a value
delete stock.milk; // remove a key
console.log(Object.keys(stock));
// [ 'tea', 'jam' ]Concept
Unpacking and copying
const { name, age } = user; creates two variables from the keys of the same names. It is called destructuring.
{ ...user } spreads all the pairs of user into a new object: a copy. A key written after the spread replaces the copied one.
The original object is not touched.
const user = { name: "Ana", age: 30 };
const { name, age } = user;
console.log(name); // Ana
const older = { ...user, age: 31 };
console.log(older.age); // 31
console.log(user.age); // 309 more exercises in the app
- 4× type the answer
- 3× multiple choice
- 1× match the pairs
- 1× fill the blanks
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.