Objects

Introduction

An array is good for a list of similar things. But a student is not a list: a student has a name, an age and some courses, and each of these means something different. An object groups related values under names called properties (or keys). Reading student.name says far more than reading student[0] would.

How it works

const student = { name: "Rahim", age: 21, courses: ["DSA", "Web"] };
student.name          // "Rahim"   (dot notation)
student["age"]        // 21        (bracket notation: the key is a string)
student.city = "Dhaka";   // adds a new property
delete student.age;       // removes one

Brackets are needed when the key is in a variable: student[key]. Reading a key that does not exist gives undefined.

Methods and this. A property that holds a function is a method. Inside it, this is the object the method was called on, so account.deposit(50) changes account's own balance:

// A method uses this to reach its own object.
const account = {
  owner: "Mitu",
  balance: 100,
  deposit(amount) {
    this.balance += amount;
    return this.balance;
  },
};
account.deposit(50);
account.deposit(25);
console.log(account.owner, "has", account.balance);
Open in compiler

Looping and unpacking.

CodeGives
Object.keys(obj)an array of the keys
Object.values(obj)an array of the values
Object.entries(obj)an array of [key, value] pairs
for (const key in obj)each key in turn
const { name, age } = student;two variables, taken from the properties (destructuring)

JSON. JSON is the text format web programs use to send data. It looks like an object literal, but keys must be in double quotes. JSON.stringify(obj) turns an object into JSON text and JSON.parse(text) turns it back. Servers and browsers exchange data this way, as you will see in the lesson on fetching data.

Objects as tallies. Because a key can come from a variable, an object can count things: counts[word] = (counts[word] ?? 0) + 1. The ?? gives 0 the first time, when the word has no count yet.

Syntax

const book = { title: "Dune", pages: 412 };
book.pages += 1;
const key = "title";
console.log(book[key]);
for (const k in book) { console.log(k, book[k]); }

Example

// An object groups values under names.
const student = { name: "Rahim", age: 21, courses: ["DSA", "Web"] };
console.log(student.name, student["age"]);
student.city = "Dhaka";           // add a property
student.courses.push("Java");     // change the array inside
const key = "city";
console.log(student[key]);
for (const k in student) {
  console.log(k, "->", student[k]);
}
const { name, age } = student;    // destructuring
console.log(name, age, JSON.stringify(student));
Open in compiler

Line by line

  1. The object has three properties, one of which is an array.
  2. The first console.log reads with a dot and with brackets.
  3. student.city = "Dhaka" adds a property, and push changes the array inside.
  4. student[key] uses the value of key, so it reads city.
  5. The for...in loop visits every key, in the order the keys were added.
  6. Destructuring makes two variables, and JSON.stringify shows the object as text.

Expected result

Rahim 21
Dhaka
name -> Rahim
age -> 21
courses -> [ 'DSA', 'Web', 'Java' ]
city -> Dhaka
Rahim 21 {"name":"Rahim","age":21,"courses":["DSA","Web","Java"],"city":"Dhaka"}

In the real world

A user profile, a product in a catalogue and a message in a chat are all objects. Almost every web service answers with JSON, which your code turns into objects with one line. Lists of objects are probably the most common data shape in all of web development.

Common mistakes

  • Writing obj.key when the key is in a variable. That looks for a property literally called "key". Use obj[key].
  • Expecting const to freeze an object. Its properties can still change.
  • Comparing objects with ===. It checks whether they are the same object.
  • Using an arrow function as a method. Arrow functions have no this of their own.

Best practices

  • Keep the shape of similar objects the same, so that code can rely on it.
  • Use destructuring to pull out the few properties you need.
  • Parse JSON once, at the edge of your program, and work with objects from then on.

Summary

Objects group values under names. Dots read fixed names and brackets read names held in variables. Methods use this to reach their own object. Object.keys, values and entries help you to loop, and JSON is the text form of an object.

Quick check

1. const p = { x: 3 }. What is p.y?
2. const key = "x". Which reads the property named x?
3. In account.deposit(50), what is this inside deposit?
4. What does JSON.stringify({ a: 1 }) give?

Key takeaways

  • Use dots for fixed names and brackets when the name is in a variable.
  • A missing property reads as undefined.
  • JSON.stringify and JSON.parse convert between objects and text.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.