In the most simple terms, an object in javascript refers to a collection of properties and methods.
Properties are like adjectives, they describe the characteristic of that object.
Methods are like verbs which describe what the object does. A method in javascript is a function that is associated with the given object it is in.
The object itself then can be thought of as a noun, something that describes a person, place or thing.
Data values that are related to each other are often grouped into an object. Keeping all these data values in one object
allows for more maintable and better organized code compare to having multiple variables floating around.
The cat pictured above can be used to illustrate javascript objects. The cat is an object with properties and methods. In javascript, objects can have one or more properties and methods. The properties and methods for this cat are:
Properties | Methods |
---|---|
cat.name = 'Fluffy' | cat.jump() |
cat.color = 'Black' | cat.eat() |
cat.age = 2 | cat.sleep() |
Properties for an object represent the attributes for that object. Properties for objects get stored as values. The example below shows how to access on objects property (using the dot notation):
// example of object with properties only.
const cat = {
name: "Fluffy",
color : "black",
age : 2
}
};
console.log(cat.age); // returns age of cat
Methods for an object typically describe what an object can do. Methods on an object are stored as functions. The example below shows how to access an the method of an object (using the dot notation):
// example of object with properties and a method.
const cat = {
name: "Fluffy",
color : "black",
age : 2,
greeting: function(){
return `hello my name is ${this.name} and I am like to nap.`;
}
};
console.log(cat.greeting()); // returns greeting