Properties and Methods
Learn about properties, methods, and the this operator.
Accessing object properties
We can access the properties of an object using dot notation. The example below shows how we can access the name
property of the elephant
object:
const yourName = 'Dumbo';const legs = 4;const fly = () => console.log('Fly, fly away!');const elephant = { yourName, legs, fly };console.log(elephant.yourName);
We can also access an object’s properties using bracket notation. The property is represented by a string inside square brackets, so it needs to be placed inside single or double quotation marks:
console.log(elephant['yourName']);
The dot notation for accessing properties is by far the most common, but
bracket notation can come in handy if the name of the property is stored as a
string. For example, if we had a variable called info
that was equal to the
string 'yourName'
, the following code would be equivalent to writing
elephant.yourName
:
const info = 'yourName';console.log(elephant[info]);
This wouldn’t work if we used elephant.info
because JavaScript would try
to find a property called info
.
In most other cases, though, we should stick to using the dot notation.
If we try to access a property that doesn’t exist, undefined
will be returned:
console.log(elephant.arms);
The in
operator can be used to check whether an object has a particular
property. So, for example, we can check if the elephant
object has properties
called arms
or legs
using the following code:
console.log('arms' in elephant);console.log('legs' in elephant);
Calling methods
Methods are just like functions, so we call them in the same way. We can refer
to the object’s method using the dot or bracket notation, just like with
properties, but with parentheses at the end. So, we would use the following
code to call the fly
method:
elephant.fly();
We can also use the square bracket notation to call methods:
elephant['fly']();