Objects in JavaScript

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:

  1. By using Object Literals
  2. By using new operator
  3. 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:

  1. Object literal is an expression
  2. It creates new object each time it appears in the code
  3. 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();

  1. new operator creates a new object
  2. new operator initialize created object also
  3. 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.

image1.gif

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:

  1. It is a static function
  2. 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:

  1. Prototype
  2. 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.

Up Next
    Ebook Download
    View all
    Learn
    View all