JavaScript

Lesson 9 of 11

Lesson ยท 12 min

Objects

Values with names

An array keeps values in order, and you find them by position. An object keeps values with names. You find a value by its name. The names are called keys, and each key with its value is a property.

const pet = {
  name: 'Biscuit',
  age: 4,
  isFriendly: true,
};

Reading and changing properties

Use a dot and the key name.

console.log(pet.name); // Biscuit
pet.age = 5;           // change a property
pet.color = 'brown';   // add a new property

As with arrays, a const object can still change. const only means that the name pet always points to the same object.

You can also use square brackets, pet['name']. This is useful when the key name is in a variable.

Objects inside arrays

Most real data is a list of objects. For example, a list of books, users, or products.

const pets = [
  { name: 'Biscuit', age: 4 },
  { name: 'Pepper', age: 2 },
];

for (const pet of pets) {
  console.log(pet.name + ' is ' + pet.age);
}

Useful tools

  • Object.keys(pet) gives an array of the key names.
  • 'name' in pet is true when the key exists.
  • An object can hold other objects and arrays.

Your turn

The object book is already in the editor. Write your code under it. The tasks build on each other, so do them in order.

Tasks

5 to do

  1. Task 1, not checked yet. Add a property named author to book. Its value is the text Tobias Lind. Use dot notation.

  2. Task 2, not checked yet. Change the value of pages to 224.

  3. Task 3, not checked yet. Make a constant summary with the text Small Engines by Tobias Lind (224 pages). Build it with a template string that reads the values from book.

  4. Task 4, not checked yet. Make a constant library. It is an array with two items: book, and a second object with title set to Night Trains and pages set to 188.

  5. Task 5, not checked yet. Use a loop to print the title of each item in library, one on each line.

Task 1 of 5

Add a property named author to book. Its value is the text Tobias Lind. Use dot notation.

All tasks

main.js

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.