Home 16: Simple objects
Content
Cancel

16: Simple objects

In this chapter, we will talk about objects. We call them simple objects for now, because in the third part of this course (object-oriented programming) we will have a closer look at objects and for now we only focus on a single part of them.

In objects you can combine multiple variables. For example, the position of an object.

1
let position = { x: 100, y: 200 };

It helps us structure our code better because we can combine all values that belong to a specific element into an object. When we have values inside an object we call them properties.

An object is defined by the opening curly braces, followed by a property name (in this example x and y), followed by a colon as assignment operator and the value of the property. If you have multiple values, they are separated by a comma ,.

!How to access elements in objects!

Here is an example with a single property:

1
let user = { name: "Garrit" };

And here is an example with a lot of properties:

1
2
3
4
5
6
let user = {
  name: "Garrit",
  role: "teacher",
  school: "JU",
  city: "Jönköping",
};

As you see, you can write an object over multiple lines, for better readability.

If we want to store the position (x and y) of multiple elements, we can either use two arrays, one for the x and one for the y position, or we can store an object inside a single array.

Storing the values inside the same object helps us to make sure that we have a x position that corresponds to a y position. We can combine values that belongs together.

You can also nest objects inside of objects:

1
2
3
4
5
6
7
let user = {
  name: "Garrit",
  role: "teacher",
  address: {
    city: "Jönköping",
  },
};
This post is licensed under CC BY 4.0 by the author.