You have already aware that JavaScript variables are containers for data values. we can say that Objects are variables too, but objects can contain many values. The values are written as name:value pairs and they are separated by a colon between them.
This code assigns a simple value “FORD” to a variable named car:
let car = "FORD";
We can assign multiple values to variable and the values are written as name:value pairs. It is a common practice to declare objects always with the const keyword.
An object definition can span multiple lines or can also be in single line, but for batter readability multiple lines are best. Let’s see how we can write this.
const car = {
Make:"FORD",
Model:"ECO-SPORT",
Color:"GRAY"
};
Example:
const Employee = {
FirstName: "John",
LastName: "Smith",
Age: 45,
Designation: "Manager",
Salary : 50000
};
Accessing Object Properties
You can access object properties in two ways which are given below:
Employee.LastName
OR
Employee["LastName"]
Key points of Objects:
- Objects can also have methods in it, see below given example.
- Methods are actions can be performed on objects.
- Methods are stored in properties as function definitions.
const Employee= {
FirstName: "John",
LastName: "Smith",
Age: 45,
Designation: "Manager",
Salary: 50000,
FullName : function() {
return this.FirstName + " " + this.LastName;
}
};
What is this keyword?
In JavaScript, this keyword refers to an object. this keyword refers to different objects depending on usage in the program.
this.FirstName
or
Employee.firstName
Key points of this keyword:
- this is not a variable. It is a keyword.
- In an object method, this refers to the object.
- Alone, this refers to the global object.
- With in a function, this refers to the global object.
- With in a function, in strict mode, this comes is undefined.
- In an event, this refers to the element that received the event.
I hope you have enjoyed reading above article. You can check more on JavaScript HERE.