Last updated on November 14, 2022
In JavaScript, objects are used to store multiple values. Usually, an object contains properties and methods. Objects are the same as variables. Usually, the variable stores a single value while the object stores multiple values.
Properties are the key value-based pair that should have a colon in the between. Following is an example,
const student = {
firstName: "James",
lastName: "Robert",
age: 12,
admissionFee : 200,
monthlyFee : 50
};
This student object has five properties which are strings and integers.
Methods are the same as JavaScript’s usual function in which any action can be done. It attaches to the property.
Let’s suppose we need to sum up the admission and monthly fee we can do it in the object by adding a method.
const student = {
firstName: "James",
lastName: "Robert",
age: 12,
admissionFee : 200,
monthlyfee : 50,
totalFee : function() {
return this.admissionFee + this.monthlyfee;
}
};
In this example, totalFee
property has a method that sums the admission and monthly fee. If you notice in the object’s method, we have this
keyword. In JavaScript, when we use this inside object, it refers to the object. In above example admissionFee
is accessed through this keyword. So this.admissionFee
returns admissionFee
property of student object. Let’s call the method into the browser console and see the result.
console.log(student.totalFee());
// Output: 250
Objects can be stored to constant and variable with both var and let keywords. Following are the examples,
Object property can be accessed through a dot property accessor and square brackets. Following is an example of a dot property accessor
object.property
Similarly, object property can be accessed through square brackets, both ways return the same result.
object[property]
Let’s access the first and last names of the student object.
console.log(student.firstName);
// Output: James
console.log(student.lastName);
// Output: Robert
We can also access the property through square brackets, the same as we access array items. Below is an example,
console.log(student['firstName']);
// Output: James
We can access the object method through the dot property accessor.
object.property + parentheses ()
Let’s access the totalFee
property to get the total fee,
console.log(student.totalFee());
// Output: 250