Learn/JavaScript/10. Structuring data
Lesson 10 of 15
Sign in

JavaScript, lesson 10

Structuring data

As programs grow, loose variables become hard to follow. Grouping related data, and the code that works on it, into one unit makes a program read like a description of the problem. In JavaScript you have two main tools: object literals for simple records and classes for things with behaviour and rules.

Object literals and shorthand

{ name, age } is shorthand for { name: name, age: age }. The spread ...pet copies all of pet's properties into a new object, which is a clean way to make a changed copy without touching the original.

Objects can hold functions too, called methods. Inside a method, this refers to the object the method was called on.

Classes

When you need many objects of the same shape with the same behaviour, write a . It is a blueprint; builds an object (an ) from it:

2 exercises to try what you just read.

Exercise 1

Bank account

Press Ctrl Enter or Check to test your code.

Exercise 2

Race times

Press Ctrl Enter or Check to test your code.

class
new
instance
  • The constructor runs once when new Counter(...) is called. It sets up the fields.
  • Methods are shared by all instances. Call them with a dot: steps.increment().
  • A getter (get value()) is a method you read like a property, with no parentheses.
  • Fields starting with # are private. Code outside the class cannot read or change steps.#count; it is a syntax error. Private fields let a class protect its rules, for example that a balance never goes negative.
  • toString() is used automatically when the object is placed in a template literal.

Static members

A static method or field belongs to the class itself, not to instances. It is a good place for helpers that create instances from other data:

Inheritance, briefly

class Dog extends Animal creates a class that starts with everything Animal has and can add or replace methods. Its constructor must call super(...) before using this. You already saw this with custom errors. Use inheritance sparingly: small classes that contain other objects are usually easier to change than deep family trees of classes.

Choosing

Use object literals for plain data, such as one line of parsed input. Use a class when the data has rules to protect or several operations that belong together.

Further reading

  • MDN: Working with objects
  • MDN: Using classes
  • MDN: Private elements
  • MDN: static

Write a class Account with:

  • a constructor taking the owner's name; the balance starts at 0 and is stored in a private field #balance;
  • deposit(amount): adds the amount;
  • withdraw(amount): subtracts it, but if the amount is larger than the balance it throws an Error with message insufficient funds and leaves the balance unchanged;
  • a getter balance that returns the current balance.

The program below your class is already written. It reads commands such as deposit 50, withdraw 20 and show, and prints Ana: 30 for show or error: insufficient funds when a withdrawal fails. The first line of input is the owner's name.

Sample input:

Sample output:

Write a class Duration that stores a length of time in whole seconds:

  • constructor(seconds) stores the total;
  • static parse(text) builds a Duration from text like 1:05:30 (hours, minutes, seconds) or 4:12 (minutes, seconds);
  • plus(other) returns a new Duration that is the sum of both;
  • toString() returns H:MM:SS, with minutes and seconds always two digits.

Each input line is one lap time. Print every lap as Lap N: H:MM:SS, then the total as Total: H:MM:SS.

Sample input:

Sample output:

const name = "Rex";
const age = 4;
const pet = { name, age, species: "dog" };   // { name: "Rex", age: 4, species: "dog" }

const { species, age: years } = pet;        // destructuring, with a rename
const older = { ...pet, age: 5 };           // copy with one property changed
console.log(species, years, older.age);     // dog 4 5
class Counter {
  #count = 0;                    // a private field

  constructor(label) {
    this.label = label;          // a public field
  }

  increment(by = 1) {
    this.#count += by;
    return this;                 // returning this allows chaining
  }

  get value() {                  // a getter: read like a property
    return this.#count;
  }

  toString() {
    return `${this.label}: ${this.#count}`;
  }
}

const steps = new Counter("steps");
steps.increment().increment(5);
console.log(steps.value);        // 6
console.log(`${steps}`);         // steps: 6
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  static parse(text) {          // Point.parse("3,4")
    const [x, y] = text.split(",").map(Number);
    return new Point(x, y);
  }

  distanceTo(other) {
    return Math.hypot(this.x - other.x, this.y - other.y);
  }
}

console.log(Point.parse("0,0").distanceTo(new Point(3, 4)));   // 5
Ana
deposit 50
withdraw 20
show
withdraw 100
show
Ana: 30
error: insufficient funds
Ana: 30
4:12
1:05:30
Lap 1: 0:04:12
Lap 2: 1:05:30
Total: 1:09:42