Javascript objects are entities that contain properties. They are basically collections of name-value pairs and methods.
const object = {
key1: value1,
key2: value2,
key3: function() {...}
}
In Javascript, almost everything is an object except the primitive data types are objects. The list of primitive types in Javascript are:
number string boolean symbol undefined null
Creating Javascript Objects
They are two ways of creating Javascript objects, one is using the object literal and the other is using the constructor.
Object literal
When creating an object using the object literal, we use the curly braces and define the key-value pairs within the curly braces.
const object = {
key: value
}
For example,
const employee = {
firstName: "Mickey",
lastName: "Mouse",
age: 10
};
Constructor
To create an object using the constructor method we use the new
keyword.
const employee = new Object();
employee.firstName = "Mickey";
employee.lastName = "Mouse";
employee.age = "10";
In this method, we use the .
literal to define the properties.
Both methods creates an object person
that has the properties firstName
, lastName
and age
.
Accessing the properties of objects
To access the properties of an object, we can use the .
or the []
symbol as follows:
const employee = {
firstName: "Mickey",
lastName: "Mouse",
age: 10
};
console.log(employee.age); // 10
console.log(employee['age']); // 10
Javascript Object methods
A function defined within an object is called an object method. Let us see with an example, how to define and access the object method.
const employee = {
firstName: "Mickey",
lastName: "Mouse",
age: 10,
fullName: function() {
console.log(this.firstName + " " + this.lastName);
}
};
employee.fullName(); // Mickey Mouse
Here, we have an object named employee
and it contains an a method fullName
which logs the full name of the employee. Notice, the fullName
is defined as a function. Hence, fullName
is the method of object employee
.