Objects

Objects are a data structure that can contain any number of properties, that can be of any data type, also arrays and other objects. Unlike arrays, the values aren't accessed by an index, but by using the property name. Properties can be read, added and removed as we please.

A property is a key-value pair. The key is used to retrieve or update the data in the value. An object to represent a person could look like this:

const myPersonObject = {
    name: "Guy Nameson",
    age : 22,
    gender : "male"
}

As arrays are encapsulated by square brackets, objects are encapsulated by curly brackets. Each key-value pair are separated by a comma (there is no comma behind the last key-value pair). The key (property name) does not need any quotes around it. The values are denoted as regular data types, e.g. strings require quotes, boolean and numbers doesn't, arrays require square brackets, and objects require curly brackets.

In the object above, we can access the properties in two ways, and which one you choose is entirely up to you.

console.log(myPersonObject["name"])

>> "Guy Nameson"

console.log(myPersonObject.name)

>> "Guy Nameson"

If you later want to add a property, you can do that by assigning the property name to a value. In the example above we have three properties (name, age, gender). When we want to add a fourth property height, we do that by typing:

console.log(myPersonObject.height)

>> undefined

myPersonObject.height = 176
console.log(myPersonObject.height)

>> 176

As you can see in the example above, if you try to print a property that doesn't exist, you will get undefined in return.

Should you want to update a property, you would reference the property and assign it a new value, just like you would any variable.

console.log(myPersonObject.name)

>> "Guy Nameson"

myPersonObjct.name = "Name Guyson"
console.log(myPersonObject.name)

>> "Name Guyson"

Properties in objects are stored by their key, not by index (as in lists). Thus when printing the entire object (console.log(myPersonObject)) the order of the properties could be in any order, defined by the environment in which you print it (terminal, browser, etc).

Last updated