5.1 basic notions

You already saw earlier in the course that objects in JavaScript are collections of key/value pairs. When several variables are strongly related, it is much better to wrap them inside an object instead of leaving them loose. Imagine an application that draws different shapes — circles, rectangles, and so on. For a circle you might be tempted to write:

let radius = 1;
let x = 0;
let y = 0;

All these variables describe the same circle, so they belong together. A better design is to put them inside one circle object using the object literal syntax:

const circle = {
  radius: 1,
  location: { x: 0, y: 0 },
  isVisible: true,
  draw() {
    console.log("draw");
  }
};

Each value can be any JavaScript type: number, string, boolean, null, undefined, another object, an array, or a function. Notice that location is itself an object with two properties, and draw is a function. Objects are not only meant to group data; they also group the operations that act on that data, like drawing or moving the circle.

From functions to methods

  • A function that lives outside any object is just called a function.
  • A function that lives inside an object is called a method — so circle.draw() is the draw method of the circle object.

Calling circle.draw() with dot notation prints our message on the console. This style — where a program is a collection of objects that send messages to each other — is called object-oriented programming, often shortened to OOP. The object literal syntax is great for one-off objects, but as applications grow we need better ways to create many similar objects, and that is what the next lessons explore.