← All lessons/Objects· Lesson 26 of 32

Meet objects

Group related values into an object literal and read them back with dot notation.

About 6 min

Keeping data together

Imagine a ball on the canvas. It has an x, a y, and a size. You *could* keep three separate variables — but they'd drift apart as your sketch grows. An object lets you bundle all of a ball's data into one tidy package.

You build an object with curly braces { }. Inside, you list properties as name: value pairs, separated by commas:

let ball = {
  x: 200,
  y: 150,
  size: 80,
};
An object literal with three properties.

Reading a property

To pull a value back out, write the object's name, a dot, and the property name. This is called dot notation: ball.x is 200, and ball.size is 80.

Build a ball, then print its properties.

Why objects?

One ball that knows its own x, y, and size is far easier to pass around and reason about than three loose variables named ballX, ballY, and ballSize.

Your turn

Make an object called ball with three properties: x set to 200, y set to 150, and size set to 80. Then println the ball's x value using ball.x.

Hints