Nearly everything in JavaScript is an Object. So understanding Objects is very essential for JavaScript programming.
Before reading this article, you may want to
go through the following articles:
In JavaScript you can create a function in many ways as in the following:
- By using Object Literals
- By using new operator
- By using Object.create()
Let us explore one by one the various options to create an object in JavaScript. Very simply you can create an Object using literals as in the following:
var student = {
name: "dj",
grade: 9,
}
You can create an empty object as in the following. We are creating an object with no properties as below:
var studentempty = {};
A complex object can be created as in the following. In the following code the studentinfo property is a complex property and takes properties of the Student object.
var sportStudent =
{
sports: "cricket",
activeyear: 4,
studentinfo :
{
name: student.name,
grade : student.grade
},
coach : "Mr Singh"
}
Some important points about creating an object using object literals are as follows:
- Object literal is an expression
- It creates new object each time it appears in the code
- A single object literal can create many objects in loop
Now let us explore how to create objects using the new operator as follows:
var student = new Object();
var studentArray = new Array();
- new operator creates a new object
- new operator initialize created object also
- new operator invokes a function as give in code above snippet.
The function invoked after the new operator is known as a constructor. For all native types JavaScript has predefined constructors.
Another way to create an object is by using the Object.create() method. You can create an object using Object.create() as in the following:
var student = Object.create(
{
name: "dj",
grade : 10
}
);
Some important points about Object.create() is as follows:
- It is a static function
- To use it pass properties like we passed name and grade to create object
When you create an object using Object.create() there are always the following two parameters to this:
- Prototype
- Properties
We will discuss prototypes in further articles. And the second parameter is properties (in the code above, name and grade) we pass to create the object.
In these ways you can create an object in JavaScript. I hope you find this article useful. Thanks for reading.