Back to: JavaScript
An object is what we call a collection of data and/or functionality that is in some way related. This could be a combination of variables and functions. When an object contains a variable, we call them properties. When an object contains a function, we call it a method.
When we create an object, we need to define and initialise it. Here is an example:
const food = {};
We have now created an empty object.
Here is the object with some data added:
const food = {
name = 'Thomas',
greeting: function() {
console.log('Hello');
}
};
When an object’s member is an object, we can reduce greeting: function() to greeting()
const food = {
name = 'Thomas',
greeting() {
console.log('Hello');
}
};
When we write an object like this we call it an object literal.
I have added what are known as members. Members consist of a name and a value. Each name and value is separated by a colon and each name-value pair is separated by a comma. The first pair is a variable, which we call a property. The second pair is a function, which we called a method.
accessing objects
dot notation
One way of accessing an object is by using dot notation. To do this, we write the name of the object, followed by a dot and then the item that is inside that object that we want to access.
Here is an example of how to access the name property in the food object that I created:
food.name
bracket notation
There is a further method for accessing objects – bracket notation.
To access the name property in the food object:
food['name']
setting object members
We can also use dot and bracket notation to set the values of members. This is done by declaring the member that we wish to set, followed by = and then the value.
If we wanted to change the value of the name property with dot notation:
food.name = 'Lara'
with bracket notation:
food['name'] = 'Lara'