What is an object?

Beginner Apr 10, 2019
Objects are structured collections of data and methods.

Like most things at this stage, we're not throwing all the information at you, so this is just a basic introduction. We've purposefully omitted all the complicated things until a later article.

Objects are like arrays but instead of indexing the elements by incremental numbers it allows you to assign a key to each value you store, separated by a ,.

So the basic syntax for declaring an object looks like this:

object = {
    key1: value1,
    key2: value2,
    ...
}

Each key-value-pair behaves just like a variable. This is especially important when you think about what can be stored inside an object. It can be anything ranging from the basic data-types, Arrays, Functions and even other objects.

object = {
    number: 1,
    float: 3.17,
    boolean: true,
    string: "Hello World",
    array: [ "John Doe", 37, 1.95 ],
    object: {
        key: value,
    },
}

The whole concept of an object can be grasped easily when you imagine it as a big cupboard with labelled drawers.

Every time you put something in a draw (e.g. a handful of socks), you assign the draw a purpose (socks) by writing a label on it. With an object we assign a key instead of writing a label:

object = {
    socks: [ "red socks", "blue socks", "black socks" ],
}

That way you can easily determine what is inside all of the drawers.

object = {
    socks: [ "red socks", "blue socks", "black socks" ],
    tops: [ "striped top", "plain top" ],
    trousers: [ "jeans", "tracksuit bottoms", "chinos", "suit bottoms" ]
}

Photo by Jan Antonin Kolar on Unsplash.