Creating objects

Imagine we have some variables to define a person:

Loading Code . . .

And now we need to pass these variables to a function:

Loading Code . . .

Yeah, it'll be a little boring. And it gets worse if we need to pass a lot of variables.

So, we can use an object instead:

Loading Code . . .

An object is a collection of properties. To create an object, we can use curly braces { } with something inside.

A property is a “key: value” pair, where a key is a string (also called a “property name”), and a value can be anything (a string, a number, a boolean, and so on).

Between key and value, we use a colon :. And to separate different properties, we use a comma ,.

In the example above, the object has three properties:

  • The first property has the key "name" and the value "John".
  • The second one has the key "age" and the value 30.
  • The third one has the key "job" and the value "teacher".

Now we can pass the whole object to the function. It'll be much easier to handle:

Loading Code . . .

If we have a lot of properties, we don't need to change the function call.

So, we can think of an object as a “container” for a set of data that represents something from the real world or something more abstract, like:

  • A person (name, age, job, etc.)
  • A game character (level, health, energy, etc.)
  • A app notification (title, text, icon, etc.)
  • A social media post (author, text, likes, comments, etc.)
  • An email (from, to, subject, body, wasRead, etc.)
  • An address (street, city, country, etc.)
  • An user (username, password, email, etc.)

Code Time

Now, let's create an object to represent a video on YouTube. Create a variable myVideo and assign to it an object with the following properties:

  • title (string)
  • author (string)
  • duration (number)
  • views (number)
  • likes (number)
  • isPublic (boolean)

The values for these properties don't matter. You can use any values you want. But you need to use the same data types as specified above.

Loading...

© 2024 - ®Mewters