Objects: how do they work?
Today we will talk about how to retrieve data from objects and a couple of pitfalls and edge cases to watch out for.
Here I have defined an object literal:
const dog = {
fur: 'brown',
eyes: 'brown',
greet: () => 'woof'
}
It has 2 properties or key-value pairs which have string values, as well as one key which has a function for a value. We call this a method.
Properties can be retrieved in one of two ways:
dog.fur
dog[someVariable]
We can use dot notation, or bracket notation - which we will discuss later. Dot notation is used when we want to look up a property on an object, and we know the name of the property we are looking up (in the above example, this is fur). So when we directly reference the property fur on dog, this will return the associated value, "brown".
console.log(dog.fur);
// "brown"
What happens if we try to reference a property that doesn't exist? For example:
console.log(dog.height);
// undefined
If we are not necessarily sure that a property exists on an object, one way we can prevent against this is by using the logical OR operator:
const value = dog.height || 10;
console.log(value);
// 10
What we are saying here is, if the property height does not exist on dog, then we want to return 10. This is part of a larger concept known as defensive coding.
What if we want to update a property on an object? Let's say we want to change dog's eyes to be green. We can reassign the property:
dog.eyes = "green";
We can use dot notation here because we know that eyes is an existing property on the object. But what would happen if we tried to do this with a property that does not exist on the object?
dog.weight = 150;
It's not going to update anything - there's no preexisting property called weight to update - rather, it will simply add a new property to the object:
console.log(dog);
{
fur: 'brown',
eyes: 'green',
greet: () => 'woof',
weight: 150
}