Skip to content
Programming contents

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:

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

JavaScript
console.log(person.name);

person.age = 31;
person.email = "ana@example.com";

console.log(person.age);
Console
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.

JavaScript
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");
  }
}
Console
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

Exercise

Create a book object with title, author and pages, and write a sentence like "Don Quixote, by Cervantes: 1,200 pages".

Show the solution
JavaScript
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.