Lesson 1.12: Objects
An object groups the data of one thing, each piece with its own name.
The idea
A person has a name, an age and a city. Instead of three separate variables, an object groups them. It goes between curly braces:
const person = {
name: "Ana",
age: 30,
city: "Seville",
};
Each piece of data is a property: a name and its value, separated by :.
Reading and changing
With a dot and the property's name:
console.log(person.name);
person.age = 31;
person.email = "ana@example.com";
console.log(person.age);
Ana
31
If the property doesn't exist, it's created, like email.
Arrays of objects
The most common shape: an array where each item is an object.
const students = [
{ name: "Ana", mark: 7 },
{ name: "Luis", mark: 4 },
{ name: "Eva", mark: 9 },
];
for (const student of students) {
if (student.mark >= 5) {
console.log(student.name + " passes");
}
}
Ana passes
Eva passes
Array or object?
- Array: several things of the same kind, in order. The fruits, the marks.
- Object: the data of a single thing, by name. A person, a book.
Try it
Create a book object with title, author and pages, and write a sentence like "Don Quixote, by Cervantes: 1,200 pages".
Show the solution
const book = {
title: "Don Quixote",
author: "Cervantes",
pages: 1200,
};
console.log(book.title + ", by " + book.author + ": " + book.pages + " pages");
Numbers are written without a thousands separator: 1200, not 1,200. In JavaScript a comma separates values, so 1,200 would be two numbers.
Summary
- An object groups the data of one thing:
{ name: "Ana" }. - You read and change it with a dot:
person.name. - An array of objects is the usual way to keep lots of similar data.