DEV Community

Si for CodeTips

Posted on • Originally published at codetips.co.uk on

What is an object?

Objects are structured collections of data and methods.

What is an object?

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,
    ...
}

Enter fullscreen mode Exit fullscreen mode

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,
    },
}

Enter fullscreen mode Exit fullscreen mode

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"],
}

Enter fullscreen mode Exit fullscreen mode

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"]
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)