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 petistruewhen 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
Task 1, not checked yet. Add a property named
authortobook. Its value is the textTobias Lind. Use dot notation.Task 2, not checked yet. Change the value of
pagesto224.Task 3, not checked yet. Make a constant
summarywith the textSmall Engines by Tobias Lind (224 pages). Build it with a template string that reads the values frombook.Task 4, not checked yet. Make a constant
library. It is an array with two items:book, and a second object withtitleset toNight Trainsandpagesset to188.Task 5, not checked yet. Use a loop to print the
titleof each item inlibrary, 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.