Bitpath

Lesson 2 · Unit 04

Objects

Values under named keys: reading, changing, nesting, unpacking and copying

13 exercisesabout 3 min

What you practise

  • Literals, dot and bracket access, adding and deleting keys, nesting, destructuring, spread, Object.keys and Object.entries, a missing key gives undefined

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?

JavaScript
const book = {
  title: "Dune",
  pages: 412,
};
console.log(book.pages);

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.

JavaScript
const user = { name: "Ana", age: 30 };
console.log(user.name);   // Ana
console.log(user["age"]); // 30
const key = "name";
console.log(user[key]);   // Ana

Concept

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.

JavaScript
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.

JavaScript
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);  // 30

9 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.

One email when Bitpath is ready to try. Nothing else. Privacy