Chapter 10
Objects
An array is a list where each item is found by its position. But position isn't always meaningful. To describe a person, you don't want "item 0" and "item 1" - you want "name" and "age." An object stores values under names of your choosing.
Creating an Object
Use curly braces { }. Inside, list name: value pairs separated by commas. Each name is called a property (or "key"):
const person = {
name: "Ada",
age: 36,
isMember: true,
};
console.log(person);This single person value now bundles three related pieces of information together, which is far tidier than three loose variables.
Reading and Changing Properties
Reach a property with a dot and its name:
const person = { name: "Ada", age: 36 };
console.log(person.name); // "Ada"
console.log(person.age); // 36
person.age = 37; // change a property
person.city = "London"; // add a brand new one
console.log(person); // { name: "Ada", age: 37, city: "London" }Assigning to a property that doesn't exist yet simply creates it. Reading one that doesn't exist gives undefined rather than an error.
Objects and Arrays Together
Properties can hold any value - including arrays and even other objects. This is how real data is shaped:
const user = {
name: "Grace",
hobbies: ["chess", "coding"],
address: {
city: "London",
postcode: "SW1",
},
};
console.log(user.hobbies[0]); // "chess"
console.log(user.address.city); // "London"You just follow the path: user, then its address, then that address's city. A list of users would be an array of objects - the most common data shape you'll ever handle.
Giving Objects Behaviour: Methods
A property can even hold a function. When it does, we call it a method - the object's own behaviour. Inside a method, the word this refers to the object it belongs to:
const dog = {
name: "Rex",
bark() {
console.log(`${this.name} says woof!`);
},
};
dog.bark(); // Rex says woof!You've actually been using methods all along: "hello".toUpperCase() and array.push() are methods on strings and arrays. Now you know what they are - functions that belong to a value.