Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Create Object in JavaScript with Example

In this example, we will learn how to create an object in JavaScript with the help of examples.

An Object in JavaScript is the template by which we can make an instance.

JavaScript is template based programming language, not class based. Therefore, we don’t need to create a class in JavaScript to get the object as like Java.

In a purely object-oriented language like Java, an object is an instance made from a class. We need to create a class before creating its object.

Since JavaScript is a template-based, not class based, therefore, we can create objects in JavaScript directly.

There are mainly three ways to create objects to manage enormous tasks and data sets within an application. They are as follows:

  • By object literal
  • By creating an instance of Object directly (using new keyword)
  • Using constructor function (using new keyword)

Let’s understand each way one by one to create an object in JavaScript with examples.

Creating an object using Object Literal in JavaScript


The simplest and the most popular way to create your own objects in JavaScript is to use object literal. The general syntax to create an object literal is as follows:

var objectName = {
      propertyName1 : value1,
      propertyName2 : value2,
      propertyName3 : value3,
      .
      .
      propertyNameN : valueN,
      functionName1 : function() {
          // code for function
      },
      functionName2 : function() {
          // code for function
      }
};

This is a simple syntax of creating an object using object literal format in JavaScript. In this syntax, we have created an object named objectName with curly braces where properties and values are separated by a colon (:).


Let’s understand it with the help of an example. In this example, we will create an object with some properties by using object literal. Look at the following snippet of code.

var person = {
 // Declaration of properties of an object person.
    firstName : "Bob",
    lastName : "Ricky",
    age : 20,
    skinColor : "White"
};

The preceding code example creates an object called person, which holds four properties: firstName, lastName, age, and skinColor.

The values contained in each property are “Bob”, “Ricky”, 20, and “White” respectively. We could access the firstName property of the object person using dot notation like this:

console.log(person.firstName);

You can also write properties with single quotes instead of double-quotes. For accessing a property of an object, the object name must be followed by a dot and the name of the property that you want access.

Example Programs based on Object Literal


1. Let’s create a simple JavaScript program in which we will create an object named person and access its various properties and display them on the browser’s console.


Output:
      First name: Ivaan
      Last name: Sagar
      Age: 18
      Skin color: White

2. Let’s create another JavaScript program in which we will create an object named student and access the various properties of a student and display them on the browser’s console. Look at the systematic snippet of code to understand better.


Output:
      First name: John
      Last name: Herry
      School name: RSVM
      Roll no: 2
      City: Dhanbad

Let’s create a JavaScript program in which we will perform the addition, subtraction, multiplication, and division of two numbers and print the results got on the browser’s console.


Output:
      Addition: 30
      Subtraction: 10
      Multiplication: 200
      Division: 2

By Creating Instance of Object


We can create an object in JavaScript directly by using a combination of a new keyword and Object() constructor function.

The new keyword and object constructor create a blank object in which we can then add properties and methods to the object using dot notation.

Each statement that adds property and function to any object must end with a semicolon.

The general syntax to create an object in JavaScript using a new keyword and Object() constructor is as follows:

var objectName = new Object(); // blank object
objectName.propertyName1 = "Value1";
objectName.propertyName2 = "Value2";
objectName.propertyName3 = "Value3";
. . . . . .
objectName.functionName1 = function()
{ 
  // function code; 
};
objectName.functionName2 = function()
{ 
  // function code; 
};

Consider the following example code.

   var school = new Object();
// Adding properties to object person.
   school.scName = "RSVM";
   school.city = "Dhanbad";
// Adding method to object school.
   school.display = function()
   {
    // function code;
   };

Let’s create a very simple JavaScript program in which we will create an instance of Object using new keyword and constructor function.


Output:
      Name of hotel: Park AV
      Rooms left in hotel: 100

In this example, we have used this keyword that refers to a current object. We can set the values of Object properties with this keyword.

Creating Many Objects in JavaScript using Constructor Notation


Sometimes, we need to create many objects to represent similar things. In this situation, we can use the constructor function to create several objects in JavaScript.

For this, we need to create a function as a template with parameters. The argument values passed we can assign to parameters inside the current object by using this keyword.

In other words, we can set the properties inside the object with this keyword. The keyword this refers to the current object. We commonly used this keyword inside functions and objects.

For example, let us consider a person object with properties like name, age, gender as given:

function person(name, age, gender)
{
// Setting properties inside the object using this keyword.
   this.name = name;
   this.age = age;
   this.gender = gender;
}

In this example, we have created a function named person who represents an object. But, we have used this keyword with properties that create a constructor.

We can use this keyword to assign values to the object’s properties based on the values passed to the function. To create a person object with data, we have to create an object variable using new keyword like this:

var per = new person("Micheal", 27, "Male");

The above statement creates per and assigns the specified value for its properties. Now, the value of per.name is the string “Micheal”, per.age is the integer 27, and so on.

You can also create many person objects with the help of new keyword. For example,

var per1 = new person("Tripti", 23, "Female");
var per2 = new person("Deep", 30, "Male");
var per3 = new person("Ivaan", 20, "Male");

Let us create a JavaScript program in which we will display the student details of the object student.

// Code for creating an object in JavaScript with Constructor functions.
Output:
      Rashmi SSLNT 5 Dhanbad

In the preceding example, we have created a constructor function for Student object type. We have assigned values to the properties of Student object using this keyword. After that, we have created a student object using new keyword.


Let’s create a JavaScript program in which we will assign values to the object’s properties by passing values to the function. We will create many objects using constructor functions and pass different values.


Output:
     Ruchi IBM 25 80000
     Tripti TCS 23 75000
     Priya Infosys 24 58000

Modifying Prototype Object in JavaScript


JavaScript provides an advanced feature object prototype that allows us to add a property to all instances of a particular object. Let’s take an example program in which we will add a few more properties using prototype property.

// JavaScript example code for modifying prototype Object.
Output:
      Employee's name: John, Age: 20 Salary: 90000
      Employee's id: 12345, Salary hike: 5500

Note:

We can use object constructor method for constructing objects in JavaScript. But, we consider it as an inferior way to create objects because of the following reasons.

1. In this method, we require more typing than object literal method.

2. Object constructor method does not perform as well in some web browsers.

3. It is more difficult to read and understand than object literal method.


In this tutorial, you learned how to create an object in JavaScript with example. Hope that you will have understood all the different ways of creating objects in JavaScript.
Thanks for reading!!!

The post How to Create Object in JavaScript with Example appeared first on Scientech Easy.



This post first appeared on Scientech Easy, please read the originial post: here

Share the post

How to Create Object in JavaScript with Example

×

Subscribe to Scientech Easy

Get updates delivered right to your inbox!

Thank you for your subscription

×